%c 转换成字符(ASCII码值,或者长度为一的字符串)
%r 优先用repr()函数进行字符串转换
%s 优先用str()函数进行字符串转换
%d、%i 转换成有符号十进制
%o 转换成无符号八进制
%x、%X 转换成无符号十六进制(Xx代表转换后的十六进制字符的大小写)
%e、%E 转成科学计数法
%f %F 转成浮点型(小数部分自然截断)
%g %G %e和%f/%E和%F的简写
%% 输出%
格式化操作符辅助指令
<span style="font-size:14px;">>>> '%x' % 108 '6c' >>> '%X' % 108 '6C' >>> '%#X' % 108 '0X6C' >>> >>> '%.2f' % 1234.456789 '1234.46' >>> '%E' % 1234.456789 '1.234457E+03' >>> '%g' % 1234.456789 '1234.46' >>> >>> '%+d' % 4 '+4' >>> '%+d' % -4 '-4' >>> 'host : %s\tPort: %d' % ('mars', 80) 'host : mars\tPort: 80' >>> 'ss\t' 'ss\t' >>> # force on ... >>> 'There are %(howmany)d %(lang)s Quotation Symbols' % {'lang':'Python', 'howmany':3} 'There are 3 Python Quotation Symbols' >>> </span>
>>> from string import Template #导入template对象 >>> s = Template('There are ${howmany} ${lang} Quotation Symbols') >>> >>> print s.substitute(lang='Python', howmany=3) There are 3 Python Quotation Symbols >>> print s.substitute(lang='Python') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.7/string.py", line 172, in substitute return self.pattern.sub(convert, self.template) File "/usr/lib64/python2.7/string.py", line 162, in convert val = mapping[named] KeyError: 'howmany' >>> print s.safe_substitute(lang='Python', howmany=3) There are 3 Python Quotation Symbols >>> print s.safe_substitute(lang='Python') There are ${howmany} Python Quotation Symbols >>>
>>> '\n' '\n' >>> print '\n' >>> r'\n' '\\n' >>> print r'\n' \n >>>
>>> str1 = 'abc' >>> str2 = 'lmn' >>> str3 = 'xyz' >>> cmp(str1, str2) -1 >>> cmp(str3, str1) 1 >>> cmp(str2, 'lmn') 0 >>>
>>> len('test') 4 >>>
>>> max('ad23xy') 'y' >>> min('zyad') 'a' >>>
>>> s = 'foobar' >>> for i,t in enumerate(s): ... print i, t ... 0 f 1 o 2 o 3 b 4 a 5 r >>>
>>> s,t = 'foo', 'bar' >>> zip(s,t) [('f', 'b'), ('o', 'a'), ('o', 'r')] >>>
>>> username = raw_input('enter your name: ') enter your name: coder >>> username 'coder' >>> len(username) 5 >>>Python里面没有C风格的结束字符NUL,你输入多少个字符,就返回多少个字符。
原文地址:http://blog.csdn.net/u012088213/article/details/44757887