Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics Functions and Looping Returning Values

What exactly does the .format do? Why do we need {} instead of the amount_due variable.

Just trying to understand fully. Why exactly is it like this : print("Each person owes ${}".format(amount_due)). And not like this: print("Each person owes $(amount_due)")

2 Answers

the {} is a place holder for a value, use the .format keyword in order to pass the variable u want into the specified place u placed the {}.

Robin Goyal
Robin Goyal
4,582 Points

F strings are another way to format strings like the way you are describing and behave very similarly to the .format method in strings. F-strings were introduced in Python 3.6 so depending on your version of Python, this won't work. If you place the character f before the first opening quote ("), you can include expressions straight into the placeholder ({}). Here are a few examples.

# Include the variable in the placeholder
>>> print(f"Each person owes ${amount_due}")

# Operations are also possible in the placeholder
>>> number_of_exclamation_marks = 10
>>> print(f"This sentence has lots of exclamation marks{'!' * number_of_exclamation_marks}")
This sentence has lots of exclamation marks!!!!!!!!!! 

As you can see, you can also have expressions (single line of code that evaluates to a value) within the placeholders as well. The f-strings way is different from the .format method but once you get the hang of it, it is a very succinct way of formatting strings.

Hope that helps anybody that was curious about this!