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

字符串常量有:

要先

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 ~~~又是一天




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值