欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python快速入门(1)简介、函数、字符串

程序员文章站 2022-07-07 08:02:25
01 python在linux中的常用命令: 进入: python #可以安装ipython,这样会自带代码提示功能 退出: exit() 进入python命令行 清屏命令: c...
01
pythonlinux中的常用命令:
进入: python
#可以安装ipython,这样会自带代码提示功能
退出: exit()

进入python命令行
清屏命令: ctrl + l
查看帮助 help() # ex. help(list)

python提供内置函数实现进制转换:
bin()
hex()



02
python文件类型:

1.源代码.py

通过下面的形式可直接运行.py文件:
在demo1.py的文件第一行加上:
#!/usr/bin/python
print 'hello,world'

然后给文件加上可执行型权限:
chmod +x demo1.py

现在可以通过如下形式执行py文件:
./demo1.py

2.字节代码
python源文件经编译后生成的扩展名为 .pyc 的文件
编译方法:
import py_compile
py_compile.compile("demo1.py")

---> 生成demo1.pyc

3.优化代码
经过优化的源文件,扩展名为 ".pyo"
>>>python -o -m py_compile demo1.py

生成demo1.pyo


python程序示例:

		#!/usr/bin/python
		# import modules used here -- sys is a very standard one
		import sys

		# gather our code in a main() function
		def main():
			print 'hello there', sys.argv[1]
			# command line args are in sys.argv[1], sys.argv[2] ...
			# sys.argv[0] is the script name itself and can be ignored

		# standard boilerplate to call the main() function to begin
		# the program.
		if __name__ == '__main__':
			main()
运行这个程序:
$ ./hello.py alice
hello there alice

函数:

		# defines a "repeat" function that takes 2 arguments.
		def repeat(s, exclaim):
			result = s + s + s # can also use "s * 3" which is faster (why?)
			#the reason being that * calculates the size of the resulting object once whereas with +, that calculation is made each time + is called
			if exclaim:
				result = result + '!!!'
			return result

函数调用:
		def main():
			print repeat('yay', false)      ## yayyayyay
			print repeat('woo hoo', true)   ## woo hoowoo hoowoo hoo!!!
缩进:

python使用4个空格作为缩进,具体可以参考如下文档:
see here: https://www.python.org/dev/peps/pep-0008/#indentation


03
python变量
查看变量内存地址:id(var)

在线帮助技巧:
help(len) -- docs for the built in len function (note here you type "len" not "len()" which would be a call to the function)
help(sys) -- overview docs for the sys module (must do an "import sys" first)
dir(sys) -- dir() is like help() but just gives a quick list of the defined symbols
help(sys.exit) -- docs for the exit() function inside of sys
help('xyz'.split) -- it turns out that the module "str" contains the built-in string code, but if you did not know that, you can call help() just using an example of the sort of call you mean: here 'xyz'.foo meaning the foo() method that runs on strings
help(list) -- docs for the built in "list" module
help(list.append) -- docs for the append() function in the list modul

04
运算符

raw_input() //从键盘获取值
ex.
a = raw_input("please input a:")
b = raw_input("please input b:")


05
数据类型
type() 可以查看某个字符的数据类型

三重引号:常用来做注释,函数中常用来做doc数据区
”“”
str
“”“

python字符串:
python strings are "immutable" which means they cannot be changed after they are created (java strings also use this immutable style).

		s = 'hi'
		s = 'hi'
		print s[1]          ## i
		print len(s)        ## 2
		print s + ' there'  ## hi there

		#print在新行中进行打印
		raw = r'this\t\n and that'   ## r'str' 表示声明的是一个原始字符串,将会原封不动的打印
		print raw     ## this\t\n and that
		
		multi = """it was the best of times.
		it was the worst of times."""
		
		
		pi = 3.14
		##text = 'the value of pi is ' + pi      ## no, does not work
		text = 'the value of pi is '  + str(pi)  ## yes

字符串常用方法:
		s.lower(), s.upper() #-- returns the lowercase or uppercase version of the string
		s.strip() #-- returns a string with whitespace removed from the start and end
		s.isalpha()/s.isdigit()/s.isspace()... #-- tests if all the string chars are in the various character classes
		s.startswith('other'), s.endswith('other') #-- tests if the string starts or ends with the given other string
		s.find('other') #-- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
		s.replace('old', 'new') #-- returns a string where all occurrences of 'old' have been replaced by 'new'
		s.split('delim') #-- returns a list of substrings separated by the given delimiter. the delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. as a convenient special case s.split() (with no arguments) splits on all whitespace chars.
		s.join(list) #-- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
更多内容可以参考如下文档:

https://docs.python.org/2/library/stdtypes.html#string-methods


字符串的格式化输出: % 运算符

		# % operator
		text = "%d little pigs come out or i'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
		
		#因为这行太长,可以用如下的方式:加括号
		# add parens to make the long-line work:
		  text = ("%d little pigs come out or i'll %s and %s and %s" %
			(3, 'huff', 'puff', 'blow down'))