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:
def swap_case(s):
new = ""
for i in range(len(s)):
if str.isupper(s[i]):
new = new + str.lower(s[i])
elif str.islower(s[i]):
new = new + str.upper(s[i])
else:
new = new + str(s[i])
return (new)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
def swap_case(s):
l = list(s)
for i in range(len(s)):
if l[i].islower():
l[i] = l[i].upper()
else:
l[i] = l[i].lower()
k = "".join(map(str,l))
return k
Python-3 in-built swapcase function.
def swap_case(s):
return s.swapcase()
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
Input:
"Pythonist 3"
Output:
"pYTHONIST 3"
As said in comments and othe answers, strings are immutable.
Try following:
s = input("Enter input: ")
def convert(ss):
# Convert it into list and then change it
newSS = list(ss)
for i,c in enumerate(newSS):
newSS[i] = c.upper() if c.islower() else c.lower()
# Convert list back to string
return ''.join(newSS)
print(s)
print(convert(s))
# Or use string build in method
print (s.swapcase())
def swap_case(s):
a=" "
for i in s:
if i==i.lower():
a=a+(i.upper())
else:
a=a+(i.lower())
return (a)
The built-in str.swapcase already does this.
def swap_case(s):
return s.swapcase()