Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert case of a string

Tags:

python

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?

like image 535
liyuhao Avatar asked Oct 15 '14 15:10

liyuhao


People also ask

How do you reverse a string in a Python case?

Use the Python string swapcase() method to return a copy of a string with all lowercase characters converted to uppercase and vice versa.

How do you reverse a case in C++?

Invert case of a string in C++The std::transform algorithm applies an operation sequentially for all the items of the specified range. This operation can be a lambda expression, a unary function, or an object implementing the () operator. It can be used as follows to invert the case of a string.

How do you reverse capitalization in Java?

Check each character, and use Character. isUpperCase / or Character. isLowerCase to test and reverse the capitalization.


4 Answers

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

like image 128
wenzul Avatar answered Oct 15 '22 07:10

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'
like image 32
ch3ka Avatar answered Oct 15 '22 07:10

ch3ka


Simply use the swapcase() method :

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

Output : mR.eD

-> This is just a two line code.

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

Happy Coding!

like image 35
Jorvis Avatar answered Oct 15 '22 07:10

Jorvis


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)
like image 20
Shehreen Khan Avatar answered Oct 15 '22 06:10

Shehreen Khan