Python 字符串 swapcase() 方法
swapcase() 方法通过将所有字符转换为相反的字母大小写(大写转换为小写,反之亦然)返回字符串。
示例
name = "JoHn CeNa"
# 将小写转换为大写,反之亦然
print(name.swapcase())
# 输出: jOhN cEnA
swapcase() 语法
swapcase() 方法的语法是:
string.swapcase()
swapcase() 参数
swapcase() 方法不接受任何参数。
swapcase() 返回值
swapcase() 方法返回:
- 字符串的大写字符转换为小写,小写字符转换为大写后的字符串。
示例 1:Python swapcase()
sentence1 = "THIS SHOULD ALL BE LOWERCASE."
# 将大写转换为小写
print(sentence1.swapcase())
sentence2 = "this should all be uppercase."
# 将小写转换为大写
print(sentence2.swapcase())
sentence3 = "ThIs ShOuLd Be MiXeD cAsEd."
# 将小写转换为大写,反之亦然
print(sentence3.swapcase())
输出
this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.
在上述示例中,我们使用了 swapcase() 方法将小写字符转换为大写,反之亦 然。
这里,
sentence1.swapcase()- 将"THIS SHOULD ALL BE LOWERCASE."中的每个大写字符转换为小写sentence2.swapcase()- 将"this should all be uppercase."中的每个小写字符转换为大写sentence3.swapcase()- 将混合字符串sentence3即"ThIs ShOuLd Be MiXeD cAsEd."转换为相反的字母大小写
示例 2:swapcase() 与非英语字符
并非总是 string.swapcase().swapcase() == string。例如,
text = "groß "
# 将文本转换为大写
print(text.swapcase())
# 对 text.swapcase() 执行 swapcase()
print(text.swapcase().swapcase())
print(text.swapcase().swapcase() == text)
输出
GROSS
gross
False
在上述示例中,我们使用了 swapcase() 方法处理德语单词 'groß'。字母 'ß' 在英语中是 'ss'。
这里,
text.swapcase()- 将'groß'转换为大写,即'GROSS'text.swapcase().swapcase()- 将'GROSS'转换为小写,即'gross'
因此新字符串 'gross' 不等于原文本。
注意: 如果你只想将字符串转换为小写,可以使用 lower()。同样,如果你只想将字符串转换为大写,可以使用 upper()。