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 (2015) Python Data Types String Formatting

ziv grinblat
ziv grinblat
190 Points

don't know how to do it

show me how, please

strings.py
name ="Ziv"
subject = "Treehouse loves {} " + format(ziv)

1 Answer

Alex Arzamendi
Alex Arzamendi
10,042 Points

Hello Ziv, we have a couple of things here that we need to know before gettin around how the code works.

First, you have a variable called name that stores the name "Ziv" which is a string value(always keep track of how your variables work and what they have, in this case is a simple scalar value such as a string)

You then introduce another variable subject that stores the result of a format expression by creating a string that parses in information via the format built in function. Notice in your code that you pass a non existent variable called ziv. This is not what you want, you want to use the information STORED inside of your variable name which is ziv, so we could very well do this in this way:

name  = "Ziv"
subject = "Treehouse loves {0}".format(name)

# Another way of doing it albeit the first option is better

subject = "Treehouse loves {0}".format("Ziv")

Why do we pass the 0 into the {}? well it is quite simple, arguments passed to the format function have a numerical order, and in almost all computer programming languages we start counting at 0, the next would be 1 and so on.

If you wanted to pass more arguments you could do this:

original_poster = "Ziv"
this_commentor = "Alex"

subject = "Treehouse loves {0}! but they also love {1}!!".format(original_poster, this_commentor)

and that is basically it! Do not forget that you can type help(<function name>) in the interactive shell to get more information or look into the comprehensive python documentation!

# inside the python shell

help("".format)

The result is an explanation in which you can find some info regarding the function, notice that in order to get the information I had to give the help() function an example of the function that I am looking into!

hope that helps!

William Li
William Li
Courses Plus Student 26,868 Points

Hi Alex, next time try post it as answer instead of comment to the question, because this is a perfectly fine answer :)