创建长的多行字符串的Pythonic方法 [英] Pythonic way to create a long multi-line string
问题描述
我的查询时间很长.我想在Python中将其拆分为几行.用JavaScript做到这一点的一种方法是使用几个句子,然后用+
运算符将它们连接起来(我知道,这可能不是最有效的方法,但是我并不真正在意此阶段的性能,只是代码可读性).示例:
I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a +
operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). Example:
var long_string = 'some text not important. just garbage to' +
'illustrate my example';
我尝试在Python中做类似的事情,但是没有用,所以我使用\
来拆分长字符串.但是,我不确定这是否是唯一/最佳/最佳的方法.看起来很尴尬.
实际代码:
I tried doing something similar in Python, but it didn't work, so I used \
to split the long string. However, I'm not sure if this is the only/best/pythonicest way of doing it. It looks awkward.
Actual code:
query = 'SELECT action.descr as "action", '\
'role.id as role_id,'\
'role.descr as role'\
'FROM '\
'public.role_action_def,'\
'public.role,'\
'public.record_def, '\
'public.action'\
'WHERE role.id = role_action_def.role_id AND'\
'record_def.id = role_action_def.def_id AND'\
'action.id = role_action_def.action_id AND'\
'role_action_def.account_id = ' + account_id + ' AND'\
'record_def.account_id=' + account_id + ' AND'\
'def_id=' + def_id
推荐答案
您是否在谈论多行字符串?很容易,使用三引号将其开始和结束.
Are you talking about multi-line strings? Easy, use triple quotes to start and end them.
s = """ this is a very
long string if I had the
energy to type more and more ..."""
您也可以使用单引号(当然在开始和结束时使用3个单引号),并将生成的字符串s
与其他任何字符串一样对待.
You can use single quotes too (3 of them of course at start and end) and treat the resulting string s
just like any other string.
注意:与任何字符串一样,引号和结尾引号之间的任何内容都将成为字符串的一部分,因此本示例中有一个前导空格(如@ root45所指出).此字符串还将包含空格和换行符.
NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.
即:
' this is a very\n long string if I had the\n energy to type more and more ...'
最后,还可以像这样在Python中构造长行:
Finally, one can also construct long lines in Python like this:
s = ("this is a very"
"long string too"
"for sure ..."
)
将不包括任何多余的空格或换行符(这是一个有意的示例,显示了跳过空格的结果将导致什么):
which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):
'this is a verylong string toofor sure ...'
不需要逗号,只需将要连接的字符串放在一对括号中,并确保考虑到任何需要的空格和换行符.
No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.
这篇关于创建长的多行字符串的Pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!