在Python中,可以使用str.ljust()、str.rjust()和str.center()方法來設(shè)置字符串的寬度。
示例代碼:
s = "Hello"
width = 10
fillchar = "-"
result = s.ljust(width, fillchar)
print(result) # 輸出:Hello-----
示例代碼:
s = "Hello"
width = 10
fillchar = "-"
result = s.rjust(width, fillchar)
print(result) # 輸出:-----Hello
示例代碼:
s = "Hello"
width = 10
fillchar = "-"
result = s.center(width, fillchar)
print(result) # 輸出:--Hello---
通過這些方法,可以方便地設(shè)置字符串的寬度和對(duì)齊方式。