参见官方文档:https://docs.python.org/zh-cn/3/library/stdtypes.html#index-36%a
会调用 ascii 函数转换任何 Python 对象。
%[ 转换标记 ][ 宽度 [ .精确度] ] 转换类型
转换标记 | 解释 | 样例 |
---|---|---|
- | 左对齐(默认右对齐) | 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"
你好
%a并不是Python中的一个占位符,正确的占位符应该是%s。%s是格式化字符串中最常用的占位符,用法示例如下:
string = "hello" print("this is a string: %s" % string)
%s占位符会被字符串string替代。
另外,%格式化字符串中有很多其他的占位符,具体可以看参考资料中的段落2。其中要注意,使用%进行格式化字符串时,如果要输出%符号,应该使用%%表示一个百分号。例如:
percent = 0.23 print("percent: %.2f%%" % (percent*100))