The assignment is:
Your task is correcting the errors in the digitized text. You only have to handle the following mistakes:
My code:
def correct(string):
for i in string:
if '5' in string:
string = string.replace('5','S')
elif '0' in string:
string = string.replace('0','O')
elif '1' in string:
string = string.replace('1','I')
return string
I know this solution will not work for a word like:
Test.assert_equals(correct("51NGAP0RE"),"SINGAPORE");
Does anyone have tips on how to make this a more general function that will work for every word?
You can use str.replace directly.
def correct(string):
return string.replace('5','S').replace('0','O').replace('1','I')
Why don't you make use of str.maketrans and str.translate:
>>> "51NGAP0RE".translate(str.maketrans('501', 'SOI'))
'SINGAPORE'
Wrapped in a function:
def correct(s):
return s.translate(str.maketrans('501', 'SOI'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With