I\'m trying to solve this challenge in hackerrank, which asks to convert all lowercase letters to uppercase letters and vice versa.
I attempt it with the following code:
Try this
def swap_case(s):
l =[]
str1 = ''
for i in s:
if i.isupper():
l.append(i.lower())
elif i.islower():
l.append(i.upper())
else:
l.append(i)
return (str1.join(l))
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
As @Julien stated in comment upper
and lower
methods return a copy, and do not change the object itself. See this docs.
EDIT @aryamccarthy reminded me of already existing feature for this kind of task in python: swapcase()
method. See more here. Note this also returns a copy of the string.
def swap_case(s):
return s.swapcase()
#or you can use list comprehension
def swap_case(s):
new=[ch.lower() if ch.isupper() else ch.upper() for ch in s]
new=''.join(new)
return new
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
def swap_case(s):
list_s= list(s)
for index,char in enumerate(list_s):
if char == char.lower():
list_s[index] =char.upper()
else:
list_s[index]= char.lower()
s = ''.join(list_s)
return s
string = 'HackerRank.com presents "Pythonist 2".'
print(swap_case(string))