用 Python 换行 [英] Wrap long lines in Python
问题描述
如何在不牺牲缩进的情况下在 Python 中换行?
How do I wrap long lines in Python without sacrificing indentation?
例如:
def fun():
print '{0} Here is a really long sentence with {1}'.format(3, 5)
假设这超过了 79 个字符的推荐限制.我阅读它的方式,这里是如何缩进它:
Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it:
def fun():
print '{0} Here is a really long \
sentence with {1}'.format(3, 5)
但是,使用这种方法,连续行的缩进与 fun()
的缩进匹配.这看起来有点丑.如果有人要检查我的代码,由于这个 print
语句,不均匀的缩进看起来会很糟糕.
However, with this approach, the indentation of the continued line matches the indentation of the fun()
. This looks kinda ugly. If someone was to go through my code, it would look bad to have uneven indentation because of this print
statement.
如何在不牺牲代码可读性的情况下有效地缩进这样的行?
How do I indent lines like this effectively without sacrificing code readability?
推荐答案
def fun():
print(('{0} Here is a really long '
'sentence with {1}').format(3, 5))
相邻的字符串文字在编译时连接起来,就像在 C 中一样.http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation 是了解更多信息的好地方.
Adjacent string literals are concatenated at compile time, just as in C. http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation is a good place to start for more info.
这篇关于用 Python 换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!