7

I'm just coming up to speed with Python and had a question about best practices (or at least common practices) around using .format on a string.

My question is mostly around when you would use blank curly brackets vs. an index number vs. a name.

For example if you had a single variable that you wanted to include in a string which one would you do?

print "I {} Stack Overflow".format(var)
print "I {0} Stack Overflow".format(var)
print "I {verb} Stack Overflow".format(verb = var)

Does this change if you have multiple variables you want to include? Maybe it's OK to include {} for a single var, but never for multiple vars?

Any thoughts or insights here would be greatly appreciated.

Thanks!

asked Jan 29, 2015 at 0:19
3
  • Im not sure what pep8 says ... but I dislike the empty braces ... and my favorite is method3 ... but thats probably just me Commented Jan 29, 2015 at 0:23
  • I tend to use {} or {word}, depending on what's more readable for the task at hand. Commented Jan 29, 2015 at 0:24
  • This, my friend, depends on your taste. :) Commented Jan 29, 2015 at 9:42

4 Answers 4

7

I don't think there are (yet) any practices established as "best" or even as "common", so you'll get a bunch of opinions (including mine:-).

I think that {named} curlies are the way to go when your format string is a variable (e.g coming from a database or config file, picked depending on user's chosen language, etc, etc) because they let you pick and choose which of the (named) arguments to format, the order, possibly repeat them, and so forth, while staying readable.

If the format string is a literal, empty curlies a la {} are least obtrusive and thus may end up most readable -- unless your format string has "too many" of them, which of course is a style judgment.

At least it's a style issue very cognate to the one you face every time you define or call a function -- how any positional arguments or parameters are "too many" for readability, should you go whole hogs to named parameters and arguments only, etc, etc. Similar considerations apply!

answered Jan 29, 2015 at 0:33
Sign up to request clarification or add additional context in comments.

4 Comments

"{:{}{}d}".format(2,0,3) only has 3 :P (I think I got the argument order right there ... )
@JoranBeasley, I agree with the implication that readability can also suffer when relatively few anonymous entries are "embricated" in unfamiliar ways. It's also interesting to note that adding arg numbers to the format string would be no help to readability either -- only names on both sides might help.
@AlexMartelli well I slightly disagree ... at least with number indexing I could tell which arguement went were :P (+1 all the same ofc because you always know your stuff :P)
@JoranBeasley, I can easily count up to 3 open-braces in string with '{:{}{}d}' -- spelling it {0:{1}{2}d} would have negative benefit for me, it only adds noise. Now '{dat:{fil}{wid}d}'.format(dat=2, fil=0, wid=3), while obviously more verbose, does add some value wrt the args' roles.
3

print " I {} Stack Overflow.".format(var) is the correct way.

If you need multiple variable you would just place more curly brackets and add the var names separated by a comma.

print "I {} Stack Overflow. It is a great {} {}!".format(var, var1, var3)
answered Jan 29, 2015 at 0:26

4 Comments

they are all "correct" ... I am curious where you get the info that empty braces are the preferred way over indexes or variable names
All three methods I describe above are valid, why do you say the empty curly bracket method is the "correct" way?
that was just how I was taught. Good to know that it can be done the other 2 ways as well. thanks
"I {feel_about} Stack Overflow.".format(feel_about="am annoyed with")
3

I know this is an old question, but Python 3.6 brings a very cool string format, called "f-strings". It's similar to Javascript. Here is an simple example:

name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")

It only works in Python 3.6 and above, but I think it's the easiest and more readable way to format strings in Python.

answered Jan 9, 2017 at 19:54

Comments

1

It's ok to use empty braces for one or two variables. I would recommend using named replacement:

  • for more variables
  • in situations where replaced string is hard to read
  • when injected var is repeated.
answered Jan 29, 2015 at 0:25

2 Comments

So you would never use the index number method?
I would use the index one when reusing a variable in the format process "{0} {1} {0}".format(a,b)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.