Python格式最佳实践 [英] Python Format Best Practices

查看:176
本文介绍了Python格式最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我只是想加快Python的速度,并且对使用.format字符串的最佳实践(或者至少是常见的做法)有疑问。我的问题主要是围绕着什么时候使用空白大括号而不是索引号与名字。



例如,如果您有一个想要包含的变量在一个字符串中你可以做什么?

  printI {} Stack Overflow.format(var)
打印I {0}堆栈溢出.format(var)
printI {verb} Stack Overflow.format(verb = var)

如果您想包含多个变量,这是否会改变?也许可以包含一个var,但从来没有多个vars?

任何想法或见解都将不胜感激。

谢谢!

解决方案

我不认为有任何做法被确立为最好,甚至常见,所以你会得到一堆的意见(包括我的: - )。

我认为 {命名} 当你的格式字符串是一个变量(例如来自数据库或配置文件,取决于用户选择的语言等),curlies是要走的路,因为它们让你挑选如果格式化字符串是一个文字,空白的卷发一个la {} 是最不引人注目的,因此可能会变得最可读 - 除非你的格式字符串中有太多的字符串,这当然是一种风格判断。 / p>

这是一个风格问题,与你每次定义或调用一个函数时所面对的风格问题非常相似 - 如果任何位置参数或参数对于可读性来说是太多的话,如果你全部使用命名参数和参数等等,等等。类似的考虑适用于!

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!

解决方案

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!

这篇关于Python格式最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆