gpt4 book ai didi

python - 如何反转(交换)字符串中每个字母的大小写?

转载 作者:太空狗 更新时间:2023-10-29 17:51:41 24 4
gpt4 key购买 nike

我正在学习 Python 并正在做这个练习:

Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string.

我的代码是:

name = 'Mr.Ed'
name_list = []

for i in name:
if i.isupper():
name_list.append(i.lower())
elif i.islower():
name_list.append(i.upper())
else:
name_list.append(i)

print(''.join(name_list))

有没有更简单直接的方法解决?

最佳答案

您可以使用 name.swapcase() 来做到这一点。查找 string methods (或查看旧版 Python 2 的 the older docs)。

关于python - 如何反转(交换)字符串中每个字母的大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com