Python - 在末尾格式化整数

标签 python python-3.x format

如何用 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/

相关文章:

python - 收集类变量中的所有实例总是不好的吗?

python - Beautifulsoup 过滤器结果在 "for i"循环中引发 KeyError

python - 什么是可变阴影?

python - Pandas 数据框中值的组合

python - python 中的打印格式

python - 如何多次运行完整的 DAG,而不是重复运行每个任务

python - 我在哪里放置 python 库文件夹?

python - 用于 Python 的 RPC 库

php - 将创建日期时间戳添加到 WooCommerce 客户电子邮件

c++ - 将文本文件输出组织到列中