python - Python 中的打印间距

标签 python string-formatting

是否可以在一行上打印多个字符串,使得最终字符串始终距左侧 x 个空格?例如,是否有办法打印与此类似的结果,其中 strZ 始终打印在同一位置(不是右对齐)?

strA strB strC        strZ 
strA                  strZ 
strC StrB strD strE   strZ

最佳答案

使用str.format :

fmt = '{:<4} {:<4} {:<4} {:<6} {:<4}'
print(fmt.format('strA', 'strB', 'strC', '', 'strZ'))
print(fmt.format('strA', '', '', '', 'strZ'))
print(fmt.format('strA', 'strB', 'strC', 'strE', 'strZ'))

打印

strA strB strC        strZ
strA                  strZ
strA strB strC strE   strZ

参见Format String Syntax .

关于python - Python 中的打印间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19661624/

相关文章:

python - 如何迭代列表列表,同时将列表中的每个值传递到 API 并在每个列表列表之后暂停?

python - 2D N 人体模拟

python - 用 2D ndarray 给出的值填充 3D ndarray 内方阵的对角线

wpf - 用 + 和 - 号格式化数字

python - Pandas - 用不同的长度对每一行进行子串

python - 在暹罗网络中使用 fit_generator 时出错

c# - 格式化字符串 % 而不将该值乘以 100

swift - 让 Str = 字符串(格式 : "لديك d٪ ثانية متبقية للاتصال", 秒)

c# - 如何格式化从文件加载的文本?

python - 使用 python 动态格式化元组元组中的字符串