python中字符串内建函数篇4

一、ljust()

语法:str.ljust(width,[fillchar])

参数说明:
width – 指定字符串长度。
fillchar – 填充字符,默认为空格。

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

str = "this is string example....wow!!!"
print(str.ljust(50, '0'))
# this is string example....wow!!!00000000

二、rjust()

语法:str.rjust(width,[fillchar])

参数说明:
width – 指定字符串长度。
fillchar – 填充字符,默认为空格。

返回值:返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

str = "this is string example....wow!!!"
print(str.rjust(40, '0'))
# 00000000this is string example....wow!!!

三、zfill(width)

语法:str.zfill(width)

width – 指定字符串的长度。原字符串右对齐,前面填充0。

返回长度为 width 的字符串,原字符串 string 右对齐,前面填充0

str = "this is string example....wow!!!"
print(str.zfill(40))
# 00000000this is string example....wow!!!
print(str.zfill(50))
# 000000000000000000this is string example....wow!!!

四、string.center(width)

语法:str.center(width, [fillchar])

width – 字符串的总宽度。fillchar – 填充字符。

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

str = 'runoob'
print(str.center(20, '*'))  
# '*******runoob*******'
print(str.center(20)) 
# '       runoob       '

猜你喜欢

转载自blog.csdn.net/m0_71422677/article/details/132105181