I am learning python and meet an exercise:
Strings. Create a function that will return another string similar to the input string, but with its case i
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'
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)
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!
#the following program is for toggle case
name=input()
for i in name:
if i.isupper():
print( i.lower(),sep='',end='')
else:
print( i.upper(),sep='',end='')
name='Mr.Ed'
print(name.swapcase())
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