%[ 转换标记 ][ 宽度 [ .精确度] ] 转换类型
转换标记 | 解释 | 样例 |
---|---|---|
- | 左对齐(默认右对齐) | print “the number is %-9f” % 1991 |
+ | 在正数后加上+ | print “the number is %+9f or %+0.9f” % (1991,-1991) |
(a space) | 正数之前保留空格 | print “the number is % 0.1f” % 1991 |
# | 显示进制标识 | print “the number is %#x” % 1991 |
0 | 位数不够0来凑 | print “the number is %010.2f” % 1991 |
# 普通占位
print "hello %s" % "world"
# 多值占位
print "hello %s,i'm %s" % ("world", "python")
# 指定占位长度
print "I‘m %s, I was born in %6s" % ('python',1991)
# I‘m python, I was born in 1991 1991占6位右对齐 相当于字符串的rjust方法
print "I‘m %s, I was born in %-6s" % ('python',1991)
# I‘m python, I was born in 1991 1991占6位左对齐 相当于字符串的ljust方法
# 字符串居中可以使用字符串的center方法
# 键值对占位
print "I‘m %(name)s, I was born in %(born)s" % {'name':'python','born':'1991'}
# 简单来说str更人性化,repr更精确。str旨在可读性上(对人),repr旨在标准上(对机器)。
print "%r" %"\n你好\n"
'\n\xe4\xbd\xa0\xe5\xa5\xbd\n'
print "%s" %"\n你好\n"
你好
[[填充符]对齐方式][符号][#][0][宽度][,][.精确度][转换类型]
对齐方式 | 解释 |
---|---|
< | 左对齐 |
> | 右对齐 |
= | 仅对数值型有效,如果有符号,在符号后数值前进行填充 |
^ | 居中对齐,用空格填充 |
符号 | 解释 |
:–: | :-: |
+ | 正数前加+,负数前加- |
- | 正数前不加符号,负数前加- |
空格 | 正数前加空格,负数前加- |
“{0}-{1}-{2}”.format(‘a’,‘b’,‘c’)
“{a}-{b}-{c}”.format(a=1,b=2,c=3)
format(1995,‘0>+10.3f’)