如何用空格填写 Python 字符串? [英] How can I fill out a Python string with spaces?

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

问题描述

我想用空格填充一个字符串.我知道以下内容适用于零:

<预><代码>>>>打印'%06d'"%4'000004'

但是当我想要这个时该怎么办?:

'嗨'

当然我可以测量字符串长度并做str+" "*leftover,但我想要最短的方法.

解决方案

您可以使用 str.ljust(width[, fillchar]):

<块引用>

返回长度为宽度的字符串中左对齐的字符串.填充是使用指定的 fillchar(默认为空格)完成的.如果 width 小于 len(s),则返回原始字符串.

<预><代码>>>>'嗨'.ljust(10)'你好 '

I want to fill out a string with spaces. I know that the following works for zero's:

>>> print  "'%06d'"%4
'000004'

But what should I do when I want this?:

'hi    '

of course I can measure string length and do str+" "*leftover, but I'd like the shortest way.

解决方案

You can do this with str.ljust(width[, fillchar]):

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).

>>> 'hi'.ljust(10)
'hi        '

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

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