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

wan muhammad najmie wan sabri
wan muhammad najmie wan sabri
1,943 Points

why is my code is wrong

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

why is this not correct

strings.py
name = "kipre"
subject = "Treehouse loves {} "
subject.format(name)

2 Answers

Gabbie Metheny
Gabbie Metheny
33,778 Points

I see two things that I think are throwing off the interpreter. First, it looks like you have a space after your curly braces, which means there will be extra whitespace at the end of your formatted string, so it won't precisely match what the challenge is asking for.

Second, since you're not printing anything, you need to call .format() directly on the string to format, rather than trying to call it on the variable. For example, if you were printing, you could do this:

name = kipre
subject = "Treehouse loves {}"
print(subject.format(name))
# output: "Treehouse loves kipre"

In this example, though, the value of subject will still be "Treehouse loves {}". For name to make it into the actual variable, you need to call .format() when setting the string. Let me know if you need further clarification!

wan muhammad najmie wan sabri
wan muhammad najmie wan sabri
1,943 Points

thank you for your explanation.

i did try another way tho since it asks to assign the changed string to subject.

name = β€œkipre” subject = β€œTreehouse loves {}” subject = subject.format(name)

it still marks me wrong for the above code. it dazzled me because i think the above should do what the outcome should be

Gabbie Metheny
Gabbie Metheny
33,778 Points

It would work, except that in Python, strings are immutable, meaning that you can't change the contents of a string directly after it's created. You can copy it and change the copy, or format when printing, but you can't assign a string to a variable and then change its value.