Python Forum

Full Version: Why this simple function doesnt work?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
>>> def correct(s):
    for c in s:
        if c=='1':
            c='I'
        if c=='5':
            c='S'
        if c=='0':
            c='O'
        else:
            c=c
    return s

>>> x = "1teruje5z t0"
>>> correct(x)
'1teruje5z t0'
W T F? Tried many things, this is simply as can be and still doesnt work.
Quote:doesnt work.
please be more specific, how does it not work?
the argument you pass is s. you iterate over it performing some operations and at the end you return s unchanged.
Moving the return line one tab forward also wont fix the problem cause it will return it after first char iteration, so what is pythonic way to do this?
I didn't suggest changing the indentation. You need to store value of c (changed or not) while iterating over s and then construct new string and return it.
and one more advise - the sooner you get rid of habit using single letter cryptic variable names - the better.
Yeah but how to do it without writing a tons of the code? Should be some lambda or 2-3 lines fast and easy way for this.
def correct(text):
    corrections = {'1':'I', '5':'S'}
    return ''.join(corrections.get(char, char) for char in text)

print(correct("1teruje5z t0"))
Output:
IterujeSz t0
Thats very elegant solution, I will remember this.Cheers
If it is one-char to one-char translation, you can do even more elegant
def correct(text):
    corrections = str.maketrans('15', 'IS') # or corrections = str.maketrans({'1':'I', '5':'S'})
    return text.translate(corrections)

print(correct("1teruje5z t0"))
this will not work for one-char to many-char-string translation