python - 如何在 Python f 字符串中指定文字字符串的宽度?

标签 python python-3.x

在 Python 3.6+ 中,可以使用 f 字符串在指定宽度的列中打印整数文字

print(f"{1:10}{2:10}{3:10}")

如何使用字符串文字做类似的事情?即,我如何在 10 个字符的列中打印“一”、“二”和“三”,而不是在 10 个字符的列中打印 1、2 和 3?

是否可以使用 f-string 和一行代码来完成,还是我必须按如下方式进行编码?

a = "One"
b = "Two"
c = "Three"
print(f"{a:10}{b:10}{c:10}"

最佳答案

您可以使用以下格式对字符串进行单行:

print(f"{'One':>10}")
#        One

查看文档 here .注意相关部分:

> Forces the field to be right-aligned within the available space (this is the default for numbers).

(已添加重点)

这就是为什么在格式化数字时不需要>

关于python - 如何在 Python f 字符串中指定文字字符串的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63065112/

相关文章:

python - 阈值处理后图像变黑

python - 谁能解释一下我知道装饰器的功能但仍然没有得到输出

python - 创建一组的所有组合并耗尽内存

python - 使用 elastic-mapreduce 将文件加载到 EMR 分布式缓存时出错

python - 编写检查所有 pandas DataFrame 列值是否满足特定值?

python - 视觉代码 pylint : unable to import webapp2 and google. appengine.api

python - mFailed 解析文本文件

python - Pylab 用表格绘图

python 2.7 到 python 3.2 字符串格式错误

python - alpine linux上gdb调试python(3)进程,无法使用py-list