How to pad a string to a fixed length with spaces in Python?

后端 未结 7 2293
别跟我提以往
别跟我提以往 2020-12-08 00:06

I\'m sure this is covered in plenty of places, but I don\'t know the exact name of the action I\'m trying to do so I can\'t really look it up. I\'ve been reading an officia

相关标签:
7条回答
  • 2020-12-08 00:30
    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
    

    This will add the number of spaces needed, provided the field has length >= the length of the name provided

    0 讨论(0)
  • 2020-12-08 00:31

    You can use the ljust method on strings.

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

    Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

    >>> name.ljust(15)[:15]
    
    0 讨论(0)
  • 2020-12-08 00:34

    Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

    def format_string(str, min_length):
        while len(str) < min_length:
            str += " "
        return str
    
    0 讨论(0)
  • 2020-12-08 00:36

    This is super simple with format:

    >>> a = "John"
    >>> "{:<15}".format(a)
    'John           '
    
    0 讨论(0)
  • 2020-12-08 00:50

    If you have python version 3.6 or higher you can use f strings

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

    Or if you'd like it to the left

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

    Centered

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

    For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax

    0 讨论(0)
  • 2020-12-08 00:56
    name = "John" // your variable
    result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                           # but cuts it at 15 characters
    
    0 讨论(0)
提交回复
热议问题