Python Forum
Why this simple function doesnt work? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why this simple function doesnt work? (/thread-15129.html)



Why this simple function doesnt work? - blackknite - Jan-05-2019

>>> 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.


RE: Why this simple function doesnt work? - Larz60+ - Jan-05-2019

Quote:doesnt work.
please be more specific, how does it not work?


RE: Why this simple function doesnt work? - buran - Jan-05-2019

the argument you pass is s. you iterate over it performing some operations and at the end you return s unchanged.


RE: Why this simple function doesnt work? - blackknite - Jan-05-2019

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?


RE: Why this simple function doesnt work? - buran - Jan-05-2019

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.


RE: Why this simple function doesnt work? - blackknite - Jan-05-2019

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.


RE: Why this simple function doesnt work? - buran - Jan-05-2019

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



RE: Why this simple function doesnt work? - blackknite - Jan-05-2019

Thats very elegant solution, I will remember this.Cheers


RE: Why this simple function doesnt work? - buran - Jan-05-2019

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