swapcase() 方法通过将所有字符转换为其相反的大小写(大写转换为小写,反之亦然)来返回字符串。
示例
name = "JoHn CeNa"
# converts lowercase to uppercase and vice versa
print(name.swapcase())
# Output: jOhN cEnA
swapcase() 语法
swapcase() 方法的语法是
string.swapcase()
swapcase() 参数
swapcase() 方法不接受任何参数。
swapcase() 返回值
swapcase() 方法返回
- 将字符串的大写字符转换为小写,小写字符转换为大写后的字符串。
示例 1:Python swapcase()
sentence1 = "THIS SHOULD ALL BE LOWERCASE."
# converts uppercase to lowercase
print(sentence1.swapcase())
sentence2 = "this should all be uppercase."
# converts lowercase to uppercase
print(sentence2.swapcase())
sentence3 = "ThIs ShOuLd Be MiXeD cAsEd."
# converts lowercase to uppercase and vice versa
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ß "
# converts text to uppercase
print(text.swapcase())
# performs swapcase() on text.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' 不等于 text。
注意:如果只想将字符串转换为小写,请使用 lower()。同样,如果只想将字符串转换为大写,请使用 upper()。
