Python - 如何用左右空格填充字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14776788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:24:19  来源:igfitidea点击:

Python - How can I pad a string with spaces from the right and left?

pythonstring

提问by Brett

I have two scenarios where I need to pad a string with whitespaces up to a certain length, in both the left and right directions (in separate cases). For instance, I have the string:

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

TEST

but I need to make the string variable

但我需要使字符串变量

_____TEST1

so that the actual string variable is 10 characters in length (led by 5 spaces in this case). NOTE: I am showing underscores to represent whitespace (the markdown doesn't look right on SO otherwise).

以便实际字符串变量的长度为 10 个字符(在这种情况下由 5 个空格引导)。 注意:我显示下划线来表示空格(否则降价在 SO 上看起来不正确)。

I also need to figure out how to reverse it and pad whitespace from the other direction:

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

TEST2_____

Are there any string helper functions to do this? Or would I need to create a character array to manage it?

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

Also note, that I am trying to keep the string length a variable (I used a length of 10 in the examples above, but I'll need to be able to change this).

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

Any help would be awesome. If there are any pythonfunctions to manage this, I'd rather avoid having to write something from the ground up.

任何帮助都是极好的。如果有任何python功能来管理这个,我宁愿避免从头开始写一些东西。

Thanks!

谢谢!

采纳答案by mgilson

You can look into str.ljustand str.rjustI believe.

你可以看看str.ljuststr.rjust我相信。

The alternative is probably to use the formatmethod:

另一种方法可能是使用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***********'

回答by ahonnecke

Python3 f string usage

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