0
my_string = test
def func_2(my_string):
    return [i+"*" for i in my_string if i!=my_string[len(my_string) - 1] else i]
print(func_2(my_string.copy()))

In the above code snippet, I need to use list comprehension to append the characters of my name with a ''. For example, in the above example, the expected result is test

But, I am getting "invalid syntax" as the error. Any insights on this would be greatly appreciated. Thanks

r.ook
  • 13,466
  • 2
  • 22
  • 39
Raakesh S
  • 21
  • 2
  • 1
    Did you mean `[i+"*" if i!=my_string[len(my_string) - 1] else i for i in my_string ]`? Please see https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions – r.ook May 17 '20 at 04:02
  • there is no `else` in the filtering clause. If you need ot use a conditional expression, put it in the main part – juanpa.arrivillaga May 17 '20 at 04:02
  • Remove the else extension –  May 17 '20 at 04:04
  • The answer bellow in good also note that you can refer to the last element in a list with index -1 and you can add a character to a variable nicely with fstrings: `[f"{c}*" if c != s[-1] else c for c in s]` – Touten May 17 '20 at 04:13

1 Answers1

1

You've switched the location of the for and if-else; The if-else should come before the for when there is an else. If there is no else, your code would be perfect. Here is a fixed version of your code:

def func_2(my_string):
    return [i+"*" if i!=my_string[len(my_string) - 1] else i for i in my_string]

Look here for more details on the syntax and use.

xilpex
  • 3,097
  • 2
  • 14
  • 45