jeudi 21 janvier 2016

if as a ternary operator python

I'm trying to take this function (which runs):

def shift_on_character(string, char):
    final = list(string)
    a = [i for index, i in enumerate(string) if i.lower() == char.lower()]
    for i in range(0,len(string)):
        if string[i] != a[0]:
            final.append(string[i])
            final.pop(0)
        else: break
   print(final)
shift_on_character("zipfian", "f")

And simplify it as much as possible. Specifically, I'm trying to use a ternary operator on the if statement to shorten that section to one line of code. I want to write:

def shift_on_character(string, char):
    final = list(string)
    a = [i for index, i in enumerate(string) if i.lower() == char.lower()]
    for i in range(0,len(string)):
        final.append(string[i]) & final.pop(0) if string[i] != a[0] else break
   print(final)
shift_on_character("zipfian", "f")

But I keep getting some random syntax error when simplifying the if statement. If I make a simpler action for the "true" condition case or if I take the else off then I still get an error which implies that python is having trouble with the "if" condition.

What's happening and how can I fix it?

Thanks!

Aucun commentaire:

Enregistrer un commentaire