How can I invert (swap) the case of each letter in a string?

Question:

I am learning Python and am working on this exercise:

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.

My code is:

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))

Is there a simpler or more direct way to solve it?

Asked By: liyuhao

||

Answers:

You can do that with name.swapcase(). Look up the string methods (or see the older docs for legacy Python 2).

Answered By: wenzul

Your solution is perfectly fine.
You don’t need three branches though, because str.upper() will return str when upper is not applicable anyway.

With generator expressions, this can be shortened to:

>>> name = 'Mr.Ed'
>>> ''.join(c.lower() if c.isupper() else c.upper() for c in name)
'mR.eD'
Answered By: ch3ka

https://github.com/suryashekhawat/pythonExamples/blob/master/string_toggle.py

    def toggle(mystr):
        arr = []
        for char in mystr:
            if char.upper() != char:
                char=char.upper()
                arr.append(char)
            else:
                char=char.lower()
                arr.append(char)
        return ''.join(map(str,arr))
    user_input = raw_input()
    output = toggle(user_input)
    print output
Answered By: Surya Pratap

Simply use the swapcase() method:

name = "Mr.Ed"
print(name.swapcase())

Output: mR.eD

Explanation:

The method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped.

Answered By: Jorvis

The following program is for toggle case

name = input()
for i in name:
    if i.isupper():
        print(i.lower(), end='')
    else:
        print(i.upper(), end='')
Answered By: krishna_mannava
name='Mr.Ed'
print(name.swapcase())
Answered By: Prabal Tiwari

In python, an inbuilt function swapcase() is present which automatically converts the case of each and every letter. Even after entering the mixture of lowercase and uppercase letters it will handle it properly and return the answer as expected.

Here is my code:

str1 = input("enter str= ")
res = str1.swapcase()
print(res)
Answered By: Shehreen Khan

changeCase lambda method reverses the case of string if the character is alpha then perform (chr(ord(char)^32) which flips the case of a alphabet. ''.join([]) converts the list to a string.

  • ord returns an Unicode code representing a character.
  • chr converts an integer to a character.

main.py

#!/usr/bin/env python3.10
changeCase = lambda x: ''.join([(chr(ord(v)^32) if 65 <= ord(v) <= 90 or 97 <= ord(v) <= 122 else v) for v in x])

print(changeCase("Dev Parzival"))
print(changeCase("Hello World!"))
print(changeCase("Haÿ"))

Output:

$ chmod +x main.py
$ ./main.py
dEV pARZIVAL
hELLO wORLD!
hAÿ
Answered By: Udesh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.