Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Meet Python Create a Variable

Brian Steyer
Brian Steyer
9,026 Points

How do I create the correct syntax for a variable when it is in the middle of a print quotation? Thanks! Brian

See attached code. Thanks! Brian

using_variables.py
favorite_color = "blue"
print("The color [favorite_color] is my favorite!")

2 Answers

In Python, you can use the .format() method to insert a piece of data into a string. However, it is simpler to take advantage of the fact that print can take in multiple values (called arguments). Python, by default, separates the values with a space.

print("The color", favorite_color, "is my favorite!")

Don't worry if the code looks confusing; it will be explained in depth in future videos

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

You have 3 options

favorite_color = "blue"

# my favorite: f-string
print(f"The color {favorite_color} is my favorite!")  # notice the f before the starting quote

# you can use .format()
print("The color {} is my favorite!".format(favorite_color))

# you can also do it like this
print("The color", favorite_color, "is my favorite!")

Heh heh there's the f-string again :)

:+1: Supported!