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

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

提交回复
热议问题