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

后端 未结 7 2374
别跟我提以往
别跟我提以往 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: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]
    

提交回复
热议问题