Question

I am writing a small script that goes through a string and finds a given character and replaces it with another.

def scrambler(string):
    sen = ''
    for c in string:
        if c.lower == 'k':
            sen += 'm'
        elif c.lower == 'o':
            sen += 'q'
        elif c.lower == 'e':
            sen += 'g'
        else:
            sen += c
    return sen

print scrambler('koe')

As you can see if the letter is 'k' then 'm' should be added to sen. For some reason the condition is not being met but I am not sure why.

Was it helpful?

Solution

You are comparing the function object c.lower with a character constant: you need to invoke the function, instead:

def scrambler(string):
    sen = ''
    for c in string:
        if c.lower() == 'k':
            sen += 'm'
        elif c.lower() == 'o':
            sen += 'q'
        elif c.lower() == 'e':
            sen += 'g'
        else:
            sen += c
    return sen

print scrambler('koe')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top