交换字符串输入参数中字母的大小写 [英] Swap case of letters in string input parameter
问题描述
我想用 Python 编写一个函数,该函数接受一个包含大小写字母的字符串作为参数,并将大写字母转换为小写,将小写字母转换为大写.
例如:
<预><代码>>>>func('DDDDDDDD')'dddDDDDD'我想用字符串来做,但我不知道怎么做.
EDIT - 比我原来的答案更简单,并且支持 ASCII 和 unicode.感谢评论者.
a = 'aBcD'a.swapcase()>>A B C D
原始答案 - 无视
a = 'aBcD'''.join(map(str.swapcase, a))>>A B C D
这会将 str.swapcase()
函数映射到字符串 a
的每个元素,交换每个字符的大小写并返回一个字符列表.>
''.join()
将列表中的每个字符连接成一个新字符串.
I would like to write a function in Python that takes a string which has lower and upper case letters as a parameter and converts upper case letters to lower case, and lower case letters to upper case.
For example:
>>> func('DDDddddd')
'dddDDDDD'
I want to do it with strings but I couldn't figure out how.
EDIT - Way simpler than my original answer, and supports both ASCII and unicode. Thanks commenters.
a = 'aBcD'
a.swapcase()
>> AbCd
Original answer - disregard
a = 'aBcD'
''.join(map(str.swapcase, a))
>> AbCd
This will map the str.swapcase()
function to each element of the string a
, swapping the case of each character and returning an list of characters.
''.join()
will join each character in the list into a new string.
这篇关于交换字符串输入参数中字母的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!