Imagine there is no built-in function to swapcase within the string class. Using
ID: 662472 • Letter: I
Question
Imagine there is no built-in function to swapcase within the string class. Using Python write your own swap case function that works like this: >>> swapcase("Hello") 'hELLO' >>> swapcase("Good Bye!") 'gOOD bYE!' Note that case swapping should only effect alphabetic letters. Try to write fairly elegant code that resorts to using ord() and chr() if and when it must. Useful operations to keep in mind include the in operator, comparison operators between strings, += operator to concatenate.
Explanation / Answer
# swapcase using ord and chr funtions
def swap(x):
if 64<x<91:
x = x-64
return chr(96+x)
elif 96<x<123:
x = x-96
return chr(64+x)
else:
return chr(x)
def swapcase(string):
return "".join( swap(x) for x in map(ord,string))
swapcase('Good Bye!')
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.