python字符串常量和使用format()函数格式化

来源:互联网 发布:挪威知乎 编辑:程序博客网 时间:2024/05/23 07:25

字符串常量有:

要先

import string

string.ascii_letters #'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'string.ascii_uppercase #'ABCDEFGHIJKLMNOPQRSTUVWXYZ'string.ascii_lowercase #'abcdefghijklmnopqrstuvwxyz'string.digits   #'0123456789'string.hexdigits #'0123456789abcdefABCDEF'string.octdigits #'01234567'string.punctuation  #'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'string.printable    #'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'string.whitespace   #' \t\n\r\x0b\x0c'


使用format()格式化字符串

"First, thou shalt count to {0}" #  引用第一个参数 
"Bring me a {}"                  #  隐式引用第一个参数
"From {} to {}"                  #  隐式引用第一个和第二个参数
"My quest is {name}"             #  引用key值为name的参数 
"Weight in tons {0.weight}"      #  引用第一个参数属性值为weight的值 
"Units destroyed: {players[0]}"  #  引用key为players为元素的第一个值

!s !r !a    分别调用str()   repr()  ascii()
"Harold's a clever {0!s}"        #  相当于引用str(第一个参数) 
"Bring out the holy {name!r}"    #  相当于引用repr(key为name的参数)
"More {!a}"                      #  相当于引用ascii(第一个参数)

'{0}, {1}, {2}'.format('a', 'b', 'c')#'a, b, c''{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only#'a, b, c''{2}, {1}, {0}'.format('a', 'b', 'c')#'c, b, a''{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence#'c, b, a''{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated#'abracadabra'


'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')#'Coordinates: 37.24N, -115.81W'coord = {'latitude': '37.24N', 'longitude': '-115.81W'}'Coordinates: {latitude}, {longitude}'.format(**coord)#'Coordinates: 37.24N, -115.81W'
zz = 1+8j"zz real is {0.real} and imag is {0.imag}".format(zz)#'zz real is 1.0 and imag is 8.0'


zz = (1,2,3)bb = (4,5,6)"{0[0]} {0[1]} {0[2]} {1[0]} {1[1]} {1[2]}".format(zz,bb)#'1 2 3 4 5 6'

使用> < ^

"{:o^30}".format(12)#'oooooooooooooo12oooooooooooooo'"{:<3}".format("1234")#'1234'"{:<66}".format("4321")#'4321                                                              '"{:>12}".format("12")#'          12'"{1:*^12}".format("a2","sh")#'*****sh*****'


还有就是使用":",后面接C中字符串%d %f%o,精度或者宽度都可以设置,没有百分号

end pos ~~~又是一天




原创粉丝点击