
[历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2014-04-02 标题python格式化输出分类编程 / python jython 标签python jython·格式化字符python格式化输出常用格式直接输出字符串格式化输出整数格式化输出16制整数格式化输出浮点数(float)格式化输出字符串(string)输出列表(list)输出字典(dictionary)python print自动换行万能的 %rPython 字符串格式化使用 “字符 %格式1 %格式2 字符”%(变量1,变量2)%格式表示接受变量的类型。常用格式格式符号 表示类型 %s 字符串 %d/%i 十进制整数 %u 十进制整数 %o 八进制整数 %x/%X 十六进制整数 %e/%E 科学计数 %f/%F 浮点数 %% 输出%以下转自【 http://www.pythonclub.org/python-basic/print 】有删改。直接输出字符串strHelloHello PythonprintstrHello#输出结果Hello Python格式化输出整数strHellothe length of (%s) is %d%(Hello World,len(Hello World))printstrHello#输出结果the length of (Hello World) is 11格式化输出16制整数nHex0x20#%x --- hex 十六进制#%d --- dec 十进制#%d --- oct 八进制printnHex %x,nDec %d,nOct %o%(nHex,nHex,nHex)#输出结果nHex 20,nDec 32,nOct 40#使用整数的各个制打印同一个数格式化输出浮点数(float)importmath#defaultprintPI %f%math.pi#width 10,precise 3,align leftprintPI %10.3f%math.pi#width 10,precise 3,align rigthprintPI %-10.3f%math.pi#前面填充字符printPI %06d%int(math.pi)#输出结果#PI 3.141593#PI 3.142#PI 3.142#PI 000003格式化输出字符串(string)#precise 3print%.3s %(jcodeer)#precise 4print%.*s%(4,jcodeer)#width 10,precise 3print%10.3s%(jcodeer)#输出结果#jco#jcod# jco输出列表(list)l[1,2,3,4,jcodeer]printl#输出结果[1, 2, 3, 4, jcodeer]#list直接打印即可输出字典(dictionary)d{1:A,2:B,3:C,4:D}printd#输出结果{1: A, 2: B, 3: C, 4: D}python print自动换行print 会自动在行末加上回车,如果不需回车只需在print语句的结尾添加一个逗号****”,“就可以改变它的行为。foriinrange(0,5):printi,或直接使用下面的函数进行输出 sys.stdout.write(输出的字串)万能的 %r%r是一个万能的格式符它会将后面给的参数原样打印出来带有类型信息。 pythonprint%r 案例 formatter%r %r %r %rprintformatter%(1,2,3,4)printformatter%(one,two,three,four)printformatter%(True,False,False,True)printformatter%(formatter,formatter,formatter,formatter)printformatter%(I had this thing.,That you could type up right.,But it didnt sing.,So I said goodnight.)输出结果 $ python ex8.py1234onetwothreefourTrueFalseFalseTrue%r %r %r %r%r %r %r %r%r %r %r %r%r %r %r %rI had this thing.That you could type up right.But it didnt sing.So I said goodnight.$