温馨提示×

Python中对如何填充和对齐字符串

小亿
317
2024-04-02 20:55:57
栏目: 编程语言

Python中有多种方法可以对字符串进行填充和对齐,以下是一些常用的方法:

  1. 使用str.ljust(), str.rjust(), str.center()方法对字符串进行填充和对齐。这些方法可以通过指定字符串的总长度和填充字符来左对齐、右对齐和居中对齐字符串。
str = "hello" print(str.ljust(10, '*')) # 输出:hello***** print(str.rjust(10, '*')) # 输出:*****hello print(str.center(10, '*')) # 输出:**hello*** 
  1. 使用字符串的format()方法进行填充和对齐。可以通过在字符串中使用{}和格式化字符来指定对齐方式和填充字符。
str = "hello" print('{:<10}'.format(str)) # 输出:hello  print('{:>10}'.format(str)) # 输出: hello print('{:^10}'.format(str)) # 输出: hello  
  1. 使用f-string进行填充和对齐。可以在字符串前面加上对齐和填充字符,然后使用f-string进行格式化。
str = "hello" print(f'{str:<10}') # 输出:hello  print(f'{str:>10}') # 输出: hello print(f'{str:^10}') # 输出: hello  

0