Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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!')