打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
在 python 中将特殊字符填充到字符串的两端实现字符串对齐

在本文中,我们将讨论如何使用“0”、空格或其他字符填充到字符串的方法。

在字符串的左侧填充

  1. zfill()方法

zfill() 方法返回指定长度的字符串,原字符串右对齐,如不满足,缺少的部分用0填补。

str1 = "abc"
print('原始字符串:', str1)
str2 = str1.zfill(6)
print('修改后字符串:' , str2)
# 输出:
原始字符串:abc
修改后字符串: 000abc
  1. rjust()方法

rjust() 返回一个原字符串右对齐,并使用空格填充设定长度的新字符串。如果指定的长度小于字符串的长度则返回原字符串。

str1 = "abc"
print('原始字符串:', str1)
str2 = str1.rjust(6)  # 默认使用空格填充
print('修改后字符串:' , str2)
str2 = str1.rjust(6,"~")  # 指定填充字符
print('修改后字符串:' , str2)
# 输出:
原始字符串:abc
修改后字符串:    abc
修改后字符串: ~~~abc

在字符串右侧填充

  1. ljust()方法

ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

str1 = "abc"
print('原始字符串:', str1)
str2 = str1.ljust(6)  # 默认使用空格填充
print('修改后字符串:' , str2, "edf")
str2 = str1.ljust(6,"~")  # 可以指定填充字符
print('修改后字符串:' , str2)
# 输出:
原始字符串:abc
修改后字符串:abc    edf
修改后字符串:abc~~~

在字符串两端填充

  1. center()方法

center() 返回一个居中的,并使用空格填充至指定长度的新字符串。默认填充字符为空格。

str1 = "abc"
print('原始字符串:', str1)
str2 = str1.center(7)  # 默认使用空格填充
print('修改后字符串:' , str2)
str2 = str1.center(7,"~")  # 可以指定填充字符
print('修改后字符串:' , str2)

# 输出:
原始字符串:abc
修改后字符串:   abc  
修改后字符串: ~~abc~~
  1. 使用 format() 实现左中右对齐
str1 = "abc"
print("{:*>7}".format(str1))  # '>':表示右对齐,长度7,用*填充,默认空格填充
print("{:*<7}".format(str1))  # '<':左对齐,长度7,用*填充,默认空格填充
print("{:*^7}".format(str1))  # '^':居中对齐,长度7,用*填充,默认空格填充
# 输出:
****abc
abc****
**abc**
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python 字符串操作2
python的字符串相关函数
python中ljust什么意思
UiPath常见的变量转换及相关函数整理
Python字符串常用方法(最全)
Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服