数字自加操作
>>> n=1 >>> n=n+1 >>> print n 2 >>> n += 1 >>> print n 3
格式化输出数字
>>> print ‘float n:%f\ninit n:%d‘ % (n,n) float n:3.000000 init n:3 >>> print ‘%0.3f‘ % n 3.000 >>> print ‘%0.4f‘ % n 3.0000 >>>
字符串切片操作
>>> s = ‘football‘ >>> s[0] ‘f‘ >>> s[0:] ‘football‘ >>> s[1:] ‘ootball‘ >>> s[1:2] ‘o‘ >>> s[:3] ‘foo‘ >>> s[1:1] ‘‘ >>> s[1:-1] ‘ootball‘ >>> s[1:0] ‘‘
字符串加法和乘法
>>> s *2 ‘footballfootball‘ >>> s += ‘a‘ >>> s ‘footballa‘ >>> print ‘-‘*20 -------------------- >>> print ‘-‘*40 ----------------------------------------
列表切片与元素赋值操作
>>> alist = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘] >>> print alist [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] >>> alist[0] ‘a‘ >>> alist[1:-1] [‘b‘, ‘c‘, ‘d‘] >>> alist[1:3] [‘b‘, ‘c‘] >>> alist[:3] [‘a‘, ‘b‘, ‘c‘] >>> alist[0]=‘f‘ >>> alist [‘f‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] >>>
元组切片操作
注:元组中的元素不能重新赋值
>>> >>> aTuple = (1,2,3,4,5,6) >>> aTuple (1, 2, 3, 4, 5, 6) >>> aTuple[:3] (1, 2, 3) >>> aTuple[5]=4 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ‘tuple‘ object does not support item assignment
字典赋值、读取、更新和key操作
>>> hostdict={‘name‘:‘server01‘,‘ip‘:‘192.168.10.10‘,‘port‘:‘8080‘} >>> hostdict {‘ip‘: ‘192.168.10.10‘, ‘name‘: ‘server01‘, ‘port‘: ‘8080‘} >>> hostdict[‘name‘] ‘server01‘ >>> hostdict[‘ip‘]=‘192.168.10.11‘ >>> hostdict {‘ip‘: ‘192.168.10.11‘, ‘name‘: ‘server01‘, ‘port‘: ‘8080‘} >>> hostdict.keys() [‘ip‘, ‘name‘, ‘port‘] >>> for key in hostdict: ... print ‘%s\t%s‘ % (key,hostdict[key]) ... ip 192.168.10.11 name server01 port 8080 >>>
列表解析
>>> a=[x + 2 for x in range(5)] >>> a [2, 3, 4, 5, 6] >>> b=[x * 2 for x in s] >>> b [‘ff‘, ‘oo‘, ‘oo‘, ‘tt‘, ‘bb‘, ‘aa‘, ‘ll‘, ‘ll‘] >>> c =[x ** 2 for x in range(8) if x % 2] >>> c [1, 9, 25, 49] >>>
dir操作获取模块的方法和属性
>>> import sys >>> dir(sys) [‘__displayhook__‘, ‘__doc__‘, ‘__egginsert‘, ‘__excepthook__‘, ‘__name__‘, ‘__package__‘, ‘__plen‘, ‘__stderr__‘, ‘__stdin__‘, ‘__stdout__‘, ‘_clear_type_cache‘, ‘_current_frames‘, ‘_getframe‘, ‘api_version‘, ‘argv‘, ‘builtin_module_names‘, ‘byteorder‘, ‘call_tracing‘, ‘callstats‘, ‘copyright‘, ‘displayhook‘, ‘dont_write_bytecode‘, ‘exc_clear‘, ‘exc_info‘, ‘exc_type‘, ‘excepthook‘, ‘exec_prefix‘, ‘executable‘, ‘exit‘, ‘flags‘, ‘float_info‘, ‘getcheckinterval‘, ‘getdefaultencoding‘, ‘getdlopenflags‘, ‘getfilesystemencoding‘, ‘getprofile‘, ‘getrecursionlimit‘, ‘getrefcount‘, ‘getsizeof‘, ‘gettrace‘, ‘hexversion‘, ‘last_traceback‘, ‘last_type‘, ‘last_value‘, ‘maxint‘, ‘maxsize‘, ‘maxunicode‘, ‘meta_path‘, ‘modules‘, ‘path‘, ‘path_hooks‘, ‘path_importer_cache‘, ‘platform‘, ‘prefix‘, ‘ps1‘, ‘ps2‘, ‘py3kwarning‘, ‘setcheckinterval‘, ‘setdlopenflags‘, ‘setprofile‘, ‘setrecursionlimit‘, ‘settrace‘, ‘stderr‘, ‘stdin‘, ‘stdout‘, ‘subversion‘, ‘version‘, ‘version_info‘, ‘warnoptions‘] >>> print sys.getfilesystemencoding <built-in function getfilesystemencoding> >>> print sys.getfilesystemencoding() UTF-8 >>>