Python center string using format specifier

前端 未结 2 937
迷失自我
迷失自我 2020-12-14 16:41

I have a string called message.

message = \"Hello, welcome!\\nThis is some text that should be centered!\"

And I\'m trying to

2条回答
  •  一整个雨季
    2020-12-14 16:53

    Here is an alternative that will auto center your text based on the longest width.

    def centerify(text, width=-1):
      lines = text.split('\n')
      width = max(map(len, lines)) if width == -1 else width
      return '\n'.join(line.center(width) for line in lines)
    
    print(centerify("Hello, welcome!\nThis is some text that should be centered!"))
    print(centerify("Hello, welcome!\nThis is some text that should be centered!", 80))
    

提交回复
热议问题