Python 字符串 swapcase() 使用方法及示例

由网友 大卫 发布 阅读 3

Python 字符串 swapcase() 使用方法及示例

Python 字符串方法

字符串swapcase()方法将给定字符串的所有大写字符转换为小写,并将所有小写字符转换为大写字符,然后将转换后的字符串返回。

swapcase()方法的格式为:

string.swapcase()

注意:不一定是 string.swapcase().swapcase() == string

字符串swapcase()参数

swapcase()方法不带任何参数。

字符串swapcase()返回值

swapcase()方法返回字符串,其中所有大写字符均转换为小写,小写字符均转换为大写。

示例1:使用swapcase()将小写交换为大写,反之亦然

# 字符串示例
string = "THIS SHOULD ALL BE LOWERCASE."
print(string.swapcase())

string = "this should all be uppercase."
print(string.swapcase())

string = "ThIs ShOuLd Be MiXeD cAsEd."
print(string.swapcase())

运行该程序时,输出为:

this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.

注意:如果只想将字符串转换为小写,请使用lower()。同样,如果要将字符串仅转换为大写,请使用upper()

Python 字符串方法

Python bin() Python 字符串 strip()