Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap case of letters in string input parameter [closed]

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.

like image 355
billwild Avatar asked Nov 16 '12 13:11

billwild


2 Answers

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.

like image 164
Aesthete Avatar answered Sep 21 '22 03:09

Aesthete


You should look into string.maketrans to create a translation table that could be used with str.translate. Other constants which will probably be useful are string.ascii_lowercase and string.ascii_uppercase.

like image 43
mgilson Avatar answered Sep 19 '22 03:09

mgilson