关于Python打印格式化与字符串,比较全面的总结,希望对大家有帮助~
# -*- coding: cp936 -*-'''打印格式'''print "a"print "b"#结果:a# bprint "a",print "b"#结果:a b 2个字符串之间有个空格print "a" + "b"#结果:ab 2个字符串之间没有空格了#换行符 \n 的用法print "hello\nworld"#结果:hello# world#制表符 \t 的用法,控制水平间隔,作用如tab键print "ABC\tDEFG"#结果:ABC DEFG \t告诉DEFG从下一个制表点开始print "Number\tSquare\tCube"for i in range (1, 11): print i,'\t',i**2,'\t',i**3'''结果:Number Square Cube1 1 12 4 83 9 274 16 645 25 1256 36 2167 49 3438 64 5129 81 72910 100 1000'''#如何打印反斜杠,把2个反斜杠放一起,第一个\告诉python接下来是一些特殊的内容#第二个告诉python这些特殊的的内容就是\字符print "hi\\there"#结果:hi\there'''格式字符串数字格式化'''#在字符串中插入字符串变量name = "lee"print "my name is %s " % name#结果: my name is lee#在字符串中插入整数变量age = 13print "i am is %i years old" % age#结果: i am is 13 years old#在字符串中插入小数变量i = 15.5 print "the num is %f" %i#结果:the num is 15.500000print "the num is %F" %i#结果:the num is 15.500000 i = 12.3456print "%.8f" % i#结果:12.34560000 位数不够就补0dec_number = 12.3456print "it is %.2f degrees today" % dec_number#结果:it is 12.35 degrees today 四舍五入了number = 12.67print "%i" % numberprint "%d" % number#结果:12 直接截断了# 12number = 12.1print "%+f" %number#结果:+12.100000print "% f" %number#结果: 12.100000 注意这2个数是对齐的,其中第二个f前面有一个空格,第二数字前面也有个空格number = 12.3456print "%e" % numberprint "%E" % number#结果:1.234560e+01# 1.234560E+01number1 = 12.3number2 = 456712345.6print "%g" %number1print "%g" %number2#结果:12.3# 4.56712e+08 g换成G一样的,g会相应的换成G,pytho会为大数自动选择e计法,较小的数选择浮点数记发