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 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!