String Built-in Functions in Python Part 4

一、bright()

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

Parameter description:
width – specifies the length of the string.
fillchar – fill character, default is space.

Return value: Returns a new string with the original string left-aligned and padded with spaces to a length of width. If the specified length is less than the length of the original string, the original string is returned.

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

Two, rjust()

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

Parameter description:
width – specifies the length of the string.
fillchar – fill character, default is space.

Return Value: Returns a new string with the original string right-aligned and padded with spaces to a length of width. If the specified length is less than the length of the original string, the original string is returned.

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

3. zfill(width)

语法:str.zfill(width)

width – Specifies the length of the string. The original string is right-aligned and filled with 0 in front.

Returns a string with a length of width, the original string is right-aligned, and the front is filled with 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!!!

Four, string.center(width)

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

width – The total width of the string. fillchar – fill character.

Returns a new string with the original string centered and padded with spaces to length width(如果不指定填充字符,默认填充符为空格)

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

Guess you like

Origin blog.csdn.net/m0_71422677/article/details/132105181