如何用 python 创建这种字符串:
" 2558. "
" 2. "
" 1224456. "
我有整数
、11 个空格和.
。
先是空格,再是整数,整数后是点,点后是空格,直到11位
我可以走了:
x = "{: d}{}".format(25, '.')
y = "|{:11s}|".format(x)
打印:
| 25. |
是否可以在一行和一个字符串中做到这一点?
最佳答案
所有建议使用算术来计算 ljust
的参数的现有答案在技术上都可行,但对我来说它们似乎不必要地复杂......似乎编写其余部分会更容易首先是字符串,然后在结果上调用 ljust,不需要算术。
for x in [2558, 2, 1224456, 25]:
s = f" {x}.".ljust(11)
print("\ninput:", x)
print("output (no pipe):", s)
print("output (with pipe):", "|" + s + "|")
结果:
input: 2558
output (no pipe): 2558.
output (with pipe): | 2558. |
input: 2
output (no pipe): 2.
output (with pipe): | 2. |
input: 1224456
output (no pipe): 1224456.
output (with pipe): | 1224456. |
input: 25
output (no pipe): 25.
output (with pipe): | 25. |
关于Python - 在末尾格式化整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58432762/