[英]Python - How can I pad a string with spaces from the right and left?
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).以便实际字符串变量的长度为 10 个字符(在这种情况下由 5 个空格引导)。 NOTE : I am showing underscores to represent whitespace (the markdown doesn't look right on SO otherwise).
注意:我显示下划线来表示空格(否则降价看起来不正确)。
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
python
functions to manage this, I'd rather avoid having to write something from the ground up.如果有任何
python
函数来管理这个,我宁愿避免从头开始写一些东西。
Thanks!谢谢!
You can look intostr.ljust
and str.rjust
I believe.我相信你可以查看
str.ljust
和str.rjust
。
The alternative is probably to use the format method:另一种方法可能是使用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***********'
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.