Markum
Markum

Reputation: 4049

Replacing variables in Python

This is my script:

fruit  = "apple"
phrase = "I like eating " + fruit + "s."

def say_fruit(fruit):
    print phrase

say_fruit('orange')

I'm trying to get say_fruit to use the string given inside the phrase variable, which actually uses the variable already assigned before to it (apple). How can I achieve this?

Upvotes: 1

Views: 123

Answers (3)

Blender
Blender

Reputation: 298076

When you run this line of code

phrase = "I like eating " + fruit + "s."

Python automatically substitutes 'apple' for fruit and phrase becomes " I like eating apples.".

I prefer using .format() to do this, as it preserves readability:

fruit  = "apple"
phrase = "I like eating {fruit}s."

def say_fruit(fruit):
    print phrase.format(fruit=fruit)

say_fruit('orange')

.format() substitutes {var} with the contents of var when called.

Upvotes: 0

Kaia
Kaia

Reputation: 891

So what you want is this, right?

>>> say_fruit('orange')
I like eating oranges.
>>> say_fruit('apples')
I like eating apples.

If so, move the definition of phrase into the function. The end result should be something like:

def say_fruit(fruit):
    phrase = "I like eating " + fruit + "s."
    print phrase

say_fruit('orange')

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

In your code, phrase is bound to a string when the module loads and is never changed. You need to be dynamic, like this:

def phrase(fruit):
    return "I like eating " + fruit + "s."

def say_fruit(fruit):
    print phrase(fruit)

Globals are just a bad idea that will haunt you in the future. Resist the temptation to use them.

Upvotes: 3

Related Questions