常见的占位符 | 解释 |
---|---|
%d | 整数 |
%f | 浮点数 |
%s | 字符串 |
%x | 十六进制整数 |
%
‘%-*s’ % (width,string) 左对齐,后补空白
‘%*s’ % (width,string) 右对齐,前补空白
%%为 % 的转义
format
例如:
age = 25
name = 'Swaroop'
print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
位置使用{1}按照使用的顺序写好,后面格式使用 .format() 写好对应的参数即可。
输出结果:
Swaroop is 25 years old
Why is Swaroop playing with that python?
补充
textwrap.fill(text,width) 指定换行符,每行显示给定宽度
eg:
text = """asdsafsdkaf
sadfsadfasd
sadfasdfsad
"""
print(text)
print(textwrap.fill(text, width=30))
#输出结果
"""
asdsafsdkaf
sadfsadfasd
sadfasdfsad
asdsafsdkaf sadfsadfasd
sadfasdfsad
"""