python字符宽度如何设置
在Python中,可以使用str.ljust()、str.rjust()和str.center()方法来设置字符串的宽度。
- str.ljust(width[, fillchar])方法会返回一个左对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。
示例代码:
s = "Hello"
width = 10
fillchar = "-"
result = s.ljust(width, fillchar)
print(result) # 输出:Hello-----
- str.rjust(width[, fillchar])方法会返回一个右对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。
示例代码:
s = "Hello"
width = 10
fillchar = "-"
result = s.rjust(width, fillchar)
print(result) # 输出:-----Hello
- str.center(width[, fillchar])方法会返回一个居中对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。
示例代码:
s = "Hello"
width = 10
fillchar = "-"
result = s.center(width, fillchar)
print(result) # 输出:--Hello---
通过这些方法,可以方便地设置字符串的宽度和对齐方式。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:vps便宜台湾vps租用多少钱 下一篇:python读取mongodb慢怎么解决
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。