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

来源:互联网 发布:淘宝老店新开的利弊 编辑:程序博客网 时间:2024/06/05 19:43
01
Python在Linux中的常用命令:
进入: 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 oneimport sys# Gather our code in a main() functiondef 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 calledif exclaim:result = result + '!!!'return result

     函数调用:
def main():print repeat('Yay', False)      ## YayYayYayprint repeat('Woo Hoo', True)   ## Woo HooWoo HooWoo Hoo!!!
      缩进:

Python使用4个空格作为缩进,具体可以参考如下文档:
see here: http://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]          ## iprint len(s)        ## 2print s + ' there'  ## hi there#print在新行中进行打印raw = r'this\t\n and that'   ## r'str' 表示声明的是一个原始字符串,将会原封不动的打印print raw     ## this\t\n and thatmulti = """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 worktext = 'The value of pi is '  + str(pi)  ## yes

     字符串常用方法:
s.lower(), s.upper() #-- returns the lowercase or uppercase version of the strings.strip() #-- returns a string with whitespace removed from the start and ends.isalpha()/s.isdigit()/s.isspace()... #-- tests if all the string chars are in the various character classess.startswith('other'), s.endswith('other') #-- tests if the string starts or ends with the given other strings.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 founds.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
      更多内容可以参考如下文档:

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


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

# % operatortext = "%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'))

0 0
原创粉丝点击