简体   繁体   中英

How to replace the right letters in a string 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?

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

Don't use elif , since that only does a test if the previous one failed. Change them all to ordinary if and the code will work correctly.

But as mentioned in the comments, there's no need for any of the tests. If the letter isn't in the string, replace() will just return the original string, so there's no harm.

string = string.replace('5', 'S').replace('0', 'O').replace('1', 'I')

Here's another method using list comprehension:

def correct(str_, replacements = {'5': 'S', '0': 'O', '1': 'I'}):
    return "".join(replacements.get(c, c) for c in str_)
print(correct("51NGAP0RE"))
#'SINGAPORE'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM