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

How are you supposed to use the .format() method without printing?

status_message = “Hey there are 7 pancakes there.” status_message = “Hey there are {} pancakes there.” print(status_message) => Hey there are {} pancakes there. print(status_message.format(2)) = > Hey there are 2 pancakes there.

I thought this was the basic method we had to use for this part. However, the question is asking me to use the .format() method without the 'print'. What am I supposed to do?

strings.py
name = 'Yungi'
subject = "Treehouse loves {}"
subject = "Treehouse loves {Yungi}"

1 Answer

Jeffrey James
Jeffrey James
2,636 Points

Here's an example of using string formatting outside of a print statement. You can think of it as a way to generate strings, using variables, which can then be used later on just as you would with any other string. Below, imagine you had to write a greeting for many people and store it somewhere to greet them later (dumb example).

Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:52:12) [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin Type "help", "copyright", "credits" or "license" for more information.

>>> people = ['Jeff', 'Chance', 'Michelle', 'Scout']
>>> messages = ["Hi, {}".format(x) for x in people]
>>> messages
['Hi, Jeff', 'Hi, Chance', 'Hi, Michelle', 'Hi, Scout']
>>> 

A more common example, let's say you have a URL:

somedomain.com/?=phrase&items=100&format=json

Say you were getting JSON data for 10 different phrases

You could use a similar pattern: phrases = ['dog', 'cat', 'bird', '......] urls = ["somedomain.com/?={}&items=100&format=json".format(x) for x in people]

Then you could get the JSON data for each url in your list of URLs.

Bruh thanks dawg