Python 字符串中常见的一些方法

 

str.capitalize()

将字符串的第一个字母变成大写,其他字母变小写。

str = "this is string example!!!"

print(str.capitalize())

结果:

This is string example!!!

 

str.title()

所有单词的首个字母转化为大写,其余字母均为小写。

str = "this is string example!!!"

print(str.title())

结果:

This Is String Example!!!

 

str.upper()

将字符串中的小写字母转为大写字母。

str = "this is string example!!!"

print(str.upper())

结果:

THIS IS STRING EXAMPLE!!!

 

str.lower()

转换字符串中所有大写字符为小写。

str = "THIS IS STRING EXAMPLE!!!"

print(str.lower())

结果:

this is string example!!!

 

str.swapcase()

对字符串的大小写字母进行转换。

str = "THIS IS STRING example!!!"

print(str.swapcase())

结果:

this is string EXAMPLE!!!

 

str.center(width[, fillchar])

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

若指定的 width 小于字符串宽度则直接返回字符串。

width -- 字符串的总宽度。

fillchar -- 填充字符。默认为空格

str = "[樱]"

print (str.center(40, '*'))

结果:

******************[樱]*******************

str.ljust(width[, fillchar])

返回一个指定的宽度 width 左对齐的字符串,fillchar 为填充的字符,默认为空格。

若指定的 width 小于字符串宽度则直接返回字符串。

width -- 字符串的总宽度。

fillchar -- 填充字符。默认为空格

str = "[樱]"

print (str.ljust(40, '*'))

结果:

[樱]*************************************


str.rjust(width[, fillchar])

返回一个指定的宽度 width 右对齐的字符串,fillchar 为填充的字符,默认为空格。

若指定的 width 小于字符串宽度则直接返回字符串。

width -- 字符串的总宽度。

fillchar -- 填充字符。默认为空格


str = "[樱]"

print (str.rjust(40, '*'))
结果:
*************************************[樱]

 

str.zfill(width)

返回一个指定的长度 width 右对齐的字符串,前面填充0。

若指定的 width 小于字符串长度则直接返回字符串。

width -- 字符串的长度。


str = "[樱]"

print (str.zfill(40))

结果:

0000000000000000000000000000000000000[樱]

 













posted @ 2018-12-12 14:34  lu11  阅读(376)  评论(0编辑  收藏  举报