Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Format Best Practices

Tags:

python

format

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!

like image 984
NimbusScale Avatar asked Jan 29 '15 00:01

NimbusScale


2 Answers

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!

like image 74
Alex Martelli Avatar answered Oct 24 '22 20:10

Alex Martelli


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)
like image 38
Brandon Pharis Avatar answered Oct 24 '22 22:10

Brandon Pharis