Best way to invert string case

I am learning python and doing an exercise:

Strings. Create a function that returns another string, similar to the input string, but with an inverted case. For example, entering β€œ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 better way to solve this problem? My decision seems strange.

+7
python
source share
4 answers

Your decision is perfect. You do not need three branches, because str.upper() will return str if the top is not applicable.

Using generator expressions, this can be reduced to:

 >>> name = 'Mr.Ed' >>> ''.join(c.lower() if c.isupper() else c.upper() for c in name) 'mR.eD' 
+12
source share

You can do this with name.swapcase() . Find string methods .

+76
source share

Just use the swapcase () method:

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

Output: mR.eD

-> This is just a two-line code.

Explanation:

The swapcase () method returns a copy of the string in which all random characters have been replaced with a case.

Happy coding!

+2
source share

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 
0
source share

All Articles