Python武器库 - 科研中常用的python字符串处理 - 字符串扩充
在python科研编程中,字符串扩充通常在处理文件名、数据集列表、或打印模型训练过程信息时非常实用,
尤其是打印模型训练过程信息时,通常需要在每一轮之间打印一行符号表示分隔,此时字符串扩充的功能尤其好用,
它能够省去手动输入字符的时间,使得输出字符串更加工整。
1. str.center(width[, fillchar])
返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。
点击查看代码
a = 'lingdu'
b = a.center(20)
c = a.center(20, '*')
print(b)
print(c)

2. str.ljust(width[, fillchar])
返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
点击查看代码
a = 'lingdu'
b = a.ljust(20)
c = a.ljust(20, '*')
print(b)
print(c)

3. str.rjust(width[, fillchar])
返回一个原字符串右对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
点击查看代码
a = 'lingdu'
b = a.rjust(20)
c = a.rjust(20, '*')
print(b)
print(c)

4. str.zfill(width)
返回指定长度的字符串,原字符串右对齐,前面填充0。
点击查看代码
a = 'lingdu'
b = a.zfill(20)
print(b)
