如何在Python中使用空格将字符串填充到固定长度?

时间:2013-12-01 06:05:35

标签: python string format

我确信这很多地方都有,但我不知道我正在尝试的动作的确切名称,所以我无法真正查找它。我一直在阅读官方的Python书30分钟,试图找出如何做到这一点。

问题:我需要在一定长度的“字段”中放置一个字符串。

例如,如果名称字段长度为15个字符,而我的名字是John,我会得到“John”后跟11个空格来创建15个字符的字段。

我需要这个用于为变量“name”输入的任何字符串。

我知道它可能是某种形式的格式化,但我找不到确切的方法来做到这一点。帮助将不胜感激。

9 个答案:

答案 0 :(得分:72)

使用format

非常简单
>>> a = "John"
>>> "{:<15}".format(a)
'John           '

答案 1 :(得分:54)

您可以使用ljust method on strings

>>> name = 'John'
>>> name.ljust(15)
'John           '

请注意,如果名称超过15个字符,ljust将不会截断它。如果您希望最终得到15个字符,则可以对结果字符串进行切片:

>>> name.ljust(15)[:15]

答案 2 :(得分:5)

如果您使用python 3.6或更高版本,则可以使用f字符串

>>> string = "John"
>>> f"{string:<15}"
'John           '

或者如果您想要它的左侧

>>> f"{string:>15}"
'          John'

居中

>>> f"{string:^15}"
'     John      '

有关更多变体,请随时查看文档:{​​{3}}

答案 3 :(得分:2)

您可以使用 rjust 和 ljust 函数在字符串之前或之后添加特定字符以达到特定长度。 number inf rjust() 方法是字符串转换后的总字符数。

numStr = '69' 
numStr = numStr.rjust(5, '*')

结果是 69***

左边:

numStr = '69' 
numStr = numStr.ljust(3, '#')

结果将是#69

还可以简单地添加零:

numstr.zfill(8)

结果是 69000000。

答案 4 :(得分:1)

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

如果字段长度> =所提供名称的长度,则会添加所需的空格数

答案 5 :(得分:1)

首先检查字符串的长度是否需要缩短,然后添加空格,直到它与字段长度一样长。

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "

答案 6 :(得分:1)

name = "John" // your variable
result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                       # but cuts it at 15 characters

答案 7 :(得分:1)

只是为了解决我的问题,它只是增加了一个空格,直到字符串的长度大于您给它的min_length。

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str

答案 8 :(得分:1)

我知道这是一个老问题,但我最终为此创建了自己的小班。

可能对某人有用,所以我会坚持下去。我使用了一个本质上是持久性的类变量,以确保添加了足够的空白来清除任何旧行。见下文:

2021-03-02 更新:稍微改进 - 在处理大型代码库时,您知道您正在编写的行是否是您关心的行,但您不知道之前写入控制台的内容以及是否要保留它。

此更新处理了这一点,您在写入控制台时更新的类变量会跟踪您当前正在写入的行是您想要保留的行,还是允许稍后覆盖。

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
overwriteLine = False
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"

    prevOverwriteLine = consolePrinter.overwriteLine
    if prevOverwriteLine:
        #Previous line entry can be overwritten, so do so
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        #Previous line entry cannot be overwritten, take a new line
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    #Update the class variable for prevOverwriteLine
    consolePrinter.overwriteLine = overwriteThisLine

    return

然后通过以下方式调用:

consolePrinter.writeline("text here", True) 

如果您希望此行可覆盖

consolePrinter.writeline("text here",False)

如果你不这样做。

请注意,要使其正常工作,推送到控制台的所有消息都需要通过 consolePrinter.writeline。