Swap case of letters in string input parameter
Solution 1
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.
Solution 2
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
.
billwild
Updated on June 27, 2022Comments
-
billwild almost 2 years
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.
-
billwild over 11 yearsi tried to do it with x.islower() or x.lower() but it print all uppercase or all lowercase. İ want to turn upper to lower, lower to upper
-
mgilson over 11 years@user1829771 -- you could do it that way too. You'd just need to build a list and then join it with
str.join
. e.g.''.join(['a','b','c'])
yields'abc'
-
Aesthete over 11 yearsYay learning is fun! I've learnt alot of python's subtleties from your answers @mgilson so I'm glad to pay it back.
-
Steven Rumbalski over 11 yearsWhy work on individual characters?
'aBcD'.swapcase()
is sufficient. -
Jon Clements over 11 yearsIf there's
str.swapcase
- why not just'Ab'.swapcase()
- d0h - beaten by Steve by 20 seconds :)? -
Aesthete over 11 yearsWow, what was I thinking. Thanks guys.