Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the right letters in a string python

Tags:

python

The assignment is:

Your task is correcting the errors in the digitized text. You only have to handle the following mistakes:

  • S is misinterpreted as 5
  • O is misinterpreted as 0
  • I is misinterpreted as 1

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?

like image 543
Steve Avatar asked Jul 24 '26 18:07

Steve


2 Answers

You can use str.replace directly.

def correct(string):
    return string.replace('5','S').replace('0','O').replace('1','I')
like image 141
Rakesh Avatar answered Jul 26 '26 09:07

Rakesh


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'))
like image 44
user3483203 Avatar answered Jul 26 '26 07:07

user3483203