How to store the output of a print statement in a for loop as a variable?

Viewed 28
for i in vl:
    if i.startswith("$"):
        print(i.split(" ")[0])

I want to store the output of that last print statement as a variable but I don't know how. Trying to save it as a variable within the for loop or after it returns a "doesn't do anything" error.

1 Answers

Define a variable before the loop and then fill it. This way the variable is present even if the if conditions are not executed.e.g.

variable = 'Default'   # create variable
for i in vl:
    if i.startswith('$'):
        variable = i.split(' ')[0]  # fill variable if the if conditions execute
print(variable)
Related