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) Logic in Python Fully Functional

Alan Sea
Alan Sea
6,781 Points

{} as str placeholders....

Why do languages like Python and Java use placeholders with the .format() method call to pass variables into strings instead of using the variable names themselves? Is it a question of style or functionality? Ultimately, at least at a basic level, both ways of writing the code seem to lead to the same result. Am I missing something?

3 Answers

Haider Ali
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Haider Ali
Python Development Techdegree Graduate 24,728 Points

Hi there Alan. Although concatenation and format give you the same result, it is a lot easier to format in your variables than to keep opening and closing strings and adding variables to them. Many programmers also consider format to be much neater. However, this is mostly just a personal preference but if you look around for some code that others have created, you will notice that a lot of people tend to use format rather than just normal concatenation. It also makes your code a lot easier to read. Another cool feature of format is you can format one thing in multiple times by just referring to its index. For example:

name = 'Alan'
message = 'Hello {0}. Hello {0}.'.format(name)
print(message)

->>>' Hello Alan. Hello Alan.

Hope this has helped.

Thanks, Haider

Alan Sea
Alan Sea
6,781 Points

Thanks for the answer! No doubt that concatenation can lead to some tricky/messy code. Definitely something to consider moving forward. I guess I'll have to get used to doing something different. Different is not always bad, I guess.

Haider Ali
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Haider Ali
Python Development Techdegree Graduate 24,728 Points

You'll get used to it :). Until recently, i never used to use format. However, I discovered that it actually makes life a lot easier!

Haha, I know. Just wondering if (i) there's a philosophical reason for not doing this or (ii) it just hasn't been prioritized.

Hmm. Why not adopt ECMA2015's approach, where variables can be called within a string? Seems much cleaner.

e.g. you can do this:

var name = "Jonny"
console.log("Hey $(name)!")