better way to invert case of string
You can do that with name.swapcase()
. Lookup the string methods.
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'
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!