Python中對(duì)如何填充和對(duì)齊字符串

小億
231
2024-04-02 20:55:57

Python中有多種方法可以對(duì)字符串進(jìn)行填充和對(duì)齊,以下是一些常用的方法:

  1. 使用str.ljust(), str.rjust(), str.center()方法對(duì)字符串進(jìn)行填充和對(duì)齊。這些方法可以通過(guò)指定字符串的總長(zhǎng)度和填充字符來(lái)左對(duì)齊、右對(duì)齊和居中對(duì)齊字符串。
str = "hello"
print(str.ljust(10, '*'))  # 輸出:hello*****
print(str.rjust(10, '*'))  # 輸出:*****hello
print(str.center(10, '*'))  # 輸出:**hello***
  1. 使用字符串的format()方法進(jìn)行填充和對(duì)齊。可以通過(guò)在字符串中使用{}和格式化字符來(lái)指定對(duì)齊方式和填充字符。
str = "hello"
print('{:<10}'.format(str))  # 輸出:hello     
print('{:>10}'.format(str))  # 輸出:     hello
print('{:^10}'.format(str))  # 輸出:  hello   
  1. 使用f-string進(jìn)行填充和對(duì)齊??梢栽谧址懊婕由蠈?duì)齊和填充字符,然后使用f-string進(jìn)行格式化。
str = "hello"
print(f'{str:<10}')  # 輸出:hello     
print(f'{str:>10}')  # 輸出:     hello
print(f'{str:^10}')  # 輸出:  hello   

0