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

.format method confusion

I don't understand how to use the .format() method without the print() function. I created 'name' and 'subject' variables and assigned them string values. But where do I apply the .format() if not as a part of the print function?

I also tried:

name = 'Joe'
subject = 'Treehouse loves '
subject.format(name)

That also failed

strings.py
name='Joe'
subject = 'Treehouse loves {}'
print(subject.format(name))

3 Answers

Hi Joe,

You can call .format() on a string directly. The parameters passed into .format()'s parentheses are inserted, in turn, at each brace pair, {}.

Something like,

name = "Steve"
today = "Thursday"
training = "80km bike"
output_string - "My name is {} and today is {}. Tomorrow, I'm doing an {}.".format(name, today, training)

That should produce a blatant lie that is "My name is Steve and today is Thursday. Tomorrow, I'm doing an 80km bike."

I hope that helps,

Steve.

andren
andren
28,558 Points

Any method that can be called on a variable of a certain type, like the subject variable which is a string, can also be called on the value directly without being stored in a variable first.

The task wants you to use it directly on the string as you assign it like this:

name='Joe'
subject = 'Treehouse loves {}'.format(name)

Thank you! when I tried that the first time I was given an error message that said 'Step 1 no longer passes'. Maybe it was a glitch? At any rate, I appreciate the help!