Python の文字列組み込み関数 パート 4

一、明るい()

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

パラメータの説明:
width – 文字列の長さを指定します。
fillchar – 塗りつぶし文字、デフォルトはスペースです。

戻り値: 元の文字列を左揃えにし、width の長さまでスペースを埋め込んだ新しい文字列を返します。指定した長さが元の文字列の長さより短い場合は、元の文字列が返されます。

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

2、rjust()

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

パラメータの説明:
width – 文字列の長さを指定します。
fillchar – 塗りつぶし文字、デフォルトはスペースです。

戻り値: 元の文字列を右揃えにし、width の長さまでスペースを埋め込んだ新しい文字列を返します。指定した長さが元の文字列の長さより短い場合は、元の文字列が返されます。

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

3.zfill(幅)

语法:str.zfill(width)

width – 文字列の長さを指定します。元の文字列は右揃えで前に 0 が埋め込まれます。

width の長さの文字列を返します。元の文字列は右揃えで、先頭は 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