python字符宽度如何设置

   2025-02-15 6550
核心提示:在Python中,可以使用str.ljust()、str.rjust()和str.center()方法来设置字符串的宽度。str.ljust(width[, fillchar])方法会返回

在Python中,可以使用str.ljust()、str.rjust()和str.center()方法来设置字符串的宽度。

str.ljust(width[, fillchar])方法会返回一个左对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。

示例代码:

s = "Hello"width = 10fillchar = "-"result = s.ljust(width, fillchar)print(result)  # 输出:Hello-----
str.rjust(width[, fillchar])方法会返回一个右对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。

示例代码:

s = "Hello"width = 10fillchar = "-"result = s.rjust(width, fillchar)print(result)  # 输出:-----Hello
str.center(width[, fillchar])方法会返回一个居中对齐的字符串,宽度为width。如果指定了fillchar参数,将使用fillchar作为填充字符(默认为空格)。

示例代码:

s = "Hello"width = 10fillchar = "-"result = s.center(width, fillchar)print(result)  # 输出:--Hello---

通过这些方法,可以方便地设置字符串的宽度和对齐方式。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言