在Python中,可以使用str.ljust()、str.rjust()和str.center()方法来设置字符串的宽度。
str.ljust(width[, fillchar])方法会返回一个左对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。示例代码:
s = "Hello"width = 10fillchar = "-"result = s.ljust(width, fillchar)print(result) # 输出:Hello-----str.rjust(width[, fillchar])方法会返回一个右对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。示例代码:
s = "Hello"width = 10fillchar = "-"result = s.rjust(width, fillchar)print(result) # 输出:-----Hellostr.center(width[, fillchar])方法会返回一个居中对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。示例代码:
s = "Hello"width = 10fillchar = "-"result = s.center(width, fillchar)print(result) # 输出:--Hello---通过这些方法,可以方便地设置字符串的宽度和对齐方式。

