Python - 如何用左右空格填充字符串? [英] Python - How can I pad a string with spaces from the right and left?

查看:104
本文介绍了Python - 如何用左右空格填充字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

测试

但我需要使字符串变量

_____TEST1

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

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

TEST2_____

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

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

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

谢谢!

解决方案

您可以查看 str.ljuststr.rjust 我相信.

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

<预><代码>>>>'{:<30}'.format('左对齐')'左对齐'>>>'{:>30}'.format('右对齐')'右对齐'>>>'{:^30}'.format('居中')'居中'>>>'{:*^30}'.format('center') # 使用 '*' 作为填充字符'***********中心***********'

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).

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).

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.

Thanks!

解决方案

You can look into str.ljust and str.rjust I believe.

The alternative is probably to use the format method:

>>> '{:<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***********'

这篇关于Python - 如何用左右空格填充字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆