如何在Python中使用空格将字符串填充到固定长度?
我确信很多地方都可以找到它,但是我不知道我要执行的操作的确切名称,因此我无法真正查找它。 我已经读了30分钟的Python官方书,试图找出方法。
问题:我需要将字符串放在一定长度的“字段”中。
例如,如果名称字段的长度为15个字符,而我的名字是John,则将得到“ John”,后跟11个空格以创建15个字符的字段。
我需要使用它来为变量“ name”输入任何字符串。
我知道这可能是某种格式,但是我找不到执行此操作的确切方法。 帮助将不胜感激。
6个解决方案
85 votes
这是format的超级简单:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
Games Brainiac answered 2020-07-28T19:14:47Z
60 votes
您可以在字符串上使用ljust方法。
>>> name = 'John'
>>> name.ljust(15)
'John '
请注意,如果名称长度超过15个字符,则不会截断ljust。 如果要以15个字符结尾,则可以对结果字符串进行切片:
>>> name.ljust(15)[:15]
Ismail Badawi answered 2020-07-28T19:15:12Z
1 votes
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
如果字段的长度> =提供的名称的长度,这将添加所需的空格数
Aswin Murugesh answered 2020-07-28T19:15:32Z
1 votes
首先检查是否需要缩短字符串的长度,然后添加空格直到其与字段长度一样长。
fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
rand += " "
Matt answered 2020-07-28T19:15:52Z
1 votes
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
answered 2020-07-28T19:16:07Z
1 votes
只是为了解决我的问题,它只是增加了一个空格,直到字符串的长度大于您提供的min_length为止。
def format_string(str, min_length):
while len(str) < min_length:
str += " "
return str
dragon40226 answered 2020-07-28T19:16:27Z