Python Format Best Practices

情到浓时终转凉″ 提交于 2019-12-23 09:26:19

问题


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!


回答1:


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!




回答2:


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)



回答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.




回答4:


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.


来源:https://stackoverflow.com/questions/28204936/python-format-best-practices

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!