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?
Use the Python string swapcase() method to return a copy of a string with all lowercase characters converted to uppercase and vice versa.
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.
Check each character, and use Character. isUpperCase / or Character. isLowerCase to test and reverse the capitalization.
You can do that with name.swapcase()
. Look up the string methods (or see the older docs for legacy Python 2).
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With