Linux 拨号vps windows公众号手机端

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

lewis 7年前 (2018-04-14) 阅读数 9 #程序编程
文章标签 python

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   
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门