1. """ 可以插入多行文字.
print """ abC 123' 456''" #单引号, 双引号, 也没有关系 """
2. 使用中文 utf-8编码
#coding=utf-8 #处理中文 x = "中文".decode('utf-8') y = u"中文" print len(x) # 结果为2 print len(y) # 结果为2
3. dir(str) #显示str的方法,属性
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
4. help(str.find) #显示str.find的帮助文件
help(str.find) Help on method_descriptor: find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
5. type(), 显示变量的类型
>>> a = open("temp.txt","w") >>> type(a) <type 'file'>
6. 占位符 %s, 字符串 %d, 数字
# %s 替换字符串 >>> print "This is a %s" %"test" This is a test # %s 可以自动转换数字为字符串 >>> print "This is a number %s" %2 This is a number 2 # %s 两个以上的占位符, 需要用() 刮起来 >>> print "There are two string %s and %s" %(2,"Test") There are two string 2 and Test >>> print "There are three string %s , %s and %s" %(2,"Test","TEST") There are three string 2 , Test and TEST # str.format()替换占位符的方法. >>> print "Format()function, {} {}".format("TEST",2) Format()function, TEST 2 >>> print "Format()function, {0} {1}".format("TEST",2) Format()function, TEST 2 >>> print "Format()function, {1} {0}".format("TEST",2) Format()function, 2 TEST >>> print "Format()function, {a} {b}".format(b="TEST",a=2) Format()function, 2 TEST # 用字典的方式, 替换占位符 >>> print "DICT() %(a)s + %(b)s" %{"b":"TEST","a":"A"} DICT() A + TEST
7. 文件操作
>>> a = open("tmp.txt","w") >>> a.write("TEST") # 只能写入字符串 >>> a = open("tmp.txt","r") >>> a.read() 'TEST' >>> a.read() '' # 游标已经到了最后, 需要重新设置游标位置 >>> a.seek(0) # 设置游标位置为0 >>> a.read() 'TEST'
8. 文件操作
a = open("temp.txt","w") a.write("Line1\nLine2\nLine3\nLine4\nLine5\nLine6\n") a.close() import linecache print linecache.getline("temp.txt",1) #打印temp.txt 第一行 a = linecache.getlines("temp.txt") print a #返回列表 ['Line1\n', 'Line2\n', 'Line3\n', 'Line4\n', 'Line5\n', 'Line6\n']
9. 列表删除
>>> a = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> del a[:] #清空列表里的所有元素 >>> a []