Created
June 26, 2017 06:33
-
-
Save lhsfcboy/c400b6cbffe445f356c7c67d26da7034 to your computer and use it in GitHub Desktop.
Python使用format格式化字符串
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = 'I’m like a {} chasing {}.' | |
# 按顺序格式化字符串,'I’m like a dog chasing cars.' | |
a.format('dog', 'cars') | |
# 在大括号中指定参数所在位置 | |
b = 'I prefer {1} {0} to {2} {0}' | |
b.format('food', 'Chinese', 'American') | |
# >代表右对齐,>前是要填充的字符,依次输出: | |
# 000001 | |
# 000019 | |
# 000256 | |
for i in [1, 19, 256]: | |
print('The index is {:0>6d}'.format(i)) | |
# <代表左对齐,依次输出: | |
# *--------- | |
# ****------ | |
# *******--- | |
for x in ['*', '****', '*******']: | |
progress_bar = '{:-<10}'.format(x) | |
print(progress_bar) | |
for x in [0.0001, 1e17, 3e-18]: | |
print('{:.6f}'.format(x)) # 按照小数点后6位的浮点数格式 | |
print('{:.1e}'.format(x)) # 按照小数点后1位的科学记数法格式 | |
print ('{:g}'.format(x)) # 系统自动选择最合适的格式 | |
template = '{name} is {age} years old.' | |
c = template.format(name='Tom', age=8)) # Tom is 8 years old. | |
d = template.format(age=7, name='Jerry')# Jerry is 7 years old. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment