Steve
Steve

Reputation: 363

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:

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?

Upvotes: 2

Views: 442

Answers (4)

user3483203
user3483203

Reputation: 51155

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

Upvotes: 5

pault
pault

Reputation: 43504

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'

Upvotes: 2

Barmar
Barmar

Reputation: 781004

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

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

You can use str.replace directly.

def correct(string):
    return string.replace('5','S').replace('0','O').replace('1','I')

Upvotes: 5

Related Questions