Reputation: 468
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!
Upvotes: 7
Views: 6574
Reputation: 362
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.
Upvotes: 3
Reputation: 881477
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!
Upvotes: 7
Reputation: 31
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)
Upvotes: 3
Reputation: 2063
It's ok to use empty braces for one or two variables. I would recommend using named replacement:
Upvotes: 1