【问题标题】:Python - How can I pad a string with spaces from the right and left?Python - 如何用左右空格填充字符串?
【发布时间】:2023-03-30 06:31:01
【问题描述】:

我有两种情况,我需要在左右方向(在不同的情况下)用空格填充一个字符串到一定长度。例如,我有字符串:

TEST

但我需要使字符串变量

_____TEST1

因此实际的字符串变量长度为 10 个字符(在本例中以 5 个空格开头)。 注意:我显示下划线来表示空格(否则降价在 SO 上看起来不正确)。

我还需要弄清楚如何反转它并从另一个方向填充空格:

TEST2_____

是否有任何字符串辅助函数可以做到这一点?还是我需要创建一个字符数组来管理它?

另外请注意,我试图将字符串长度保留为变量(我在上面的示例中使用了 10 的长度,但我需要能够更改它)。

任何帮助都会很棒。如果有任何 python 函数来管理它,我宁愿避免从头开始编写一些东西。

谢谢!

【问题讨论】:

标签: python string


【解决方案1】:

我相信你可以查看str.ljust and str.rjust

替代方法可能是使用format 方法:

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

【讨论】:

  • @Brett -- 看起来那些已经被弃用了。我已经更新了另一种不是 ;-)
  • str.ljustrjust 方法已弃用;您刚刚链接到来自 string 模块的古老函数,这些函数仅在 2.3 之前的版本中需要,当时内置类型不像类,并且只有方法作为特例。
  • 如何将 30 设为变量?
  • @Raksha -- 类似'{:&gt;{width}}'.format('right aligned', width=30) 的作品。
【解决方案2】:

Python3 f 字符串用法

l = "left aligned"
print(f"{l.ljust(30)}")

r = "right aligned"
print(f"{r.rjust(30)}")

c = "center aligned"
print(f"{c.center(30)}")

>>> l = "left aligned"
>>> print(f"{l.ljust(30)}")
left aligned                  

>>> r = "right aligned"
>>> print(f"{r.rjust(30)}")
                 right aligned

>>> print(f"{c.center(30)}")
        center aligned        

【讨论】:

  • 但是,这些不是 f-string 特定的,只有在您想要对齐字符串(不是数字,或者说,元组或列表)时才有效。您可以在 f-strings 中使用与 format 完全相同的语法,就像在另一个答案中一样。因此,例如:f'{right_stuff:&gt;{width}}'f'{left_stuff:&lt;{width}}'
猜你喜欢
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多