相关疑难解决方法(0)

Pythonic方式创建一个长多行字符串

我有一个很长的查询.我想在Python中将它分成几行.在JavaScript中实现它的一种方法是使用几个句子并将它们与+运算符连接(我知道,也许这不是最有效的方法,但我并不关心这个阶段的性能,只是代码可读性) .例:

var long_string = 'some text not important. just garbage to' +
                  'illustrate my example';
Run Code Online (Sandbox Code Playgroud)

我尝试在Python中做类似的事情,但它不起作用,所以我习惯\拆分长字符串.但是,我不确定这是否是唯一/最好/最好的方式.看起来很尴尬.实际代码:

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
Run Code Online (Sandbox Code Playgroud)

python string multiline multilinestring

1160
推荐指数
21
解决办法
102万
查看次数

Python正则表达式编译(使用re.VERBOSE)不起作用

我正在尝试在编译正则表达式时添加注释,但是当使用re.VERBOSE标志时,我再也没有得到任何匹配结果.

(使用Python 3.3.0)

之前:

regex = re.compile(r"Duke wann", re.IGNORECASE)
print(regex.search("He is called: Duke WAnn.").group())
Run Code Online (Sandbox Code Playgroud)

输出:Duke WAnn

后:

regex = re.compile(r'''
Duke # First name 
Wann #Last Name
''', re.VERBOSE | re.IGNORECASE)

print(regex.search("He is called: Duke WAnn.").group())`
Run Code Online (Sandbox Code Playgroud)

输出:AttributeError:'NoneType'对象没有属性'group'

python regex

9
推荐指数
1
解决办法
2523
查看次数

当包含有意义的空格时,如何编写与 re.VERBOSE 一起使用的模式?

添加 re.VERBOSE 时,包含有意义空格的正则表达式会中断,这显然是因为 re.VERBOSE“有用”地将“问题摘要”中的(有意义的)空格以及所有糟糕的无意义空格(例如填充和换行符内的(多行)模式)。(我在多行中使用 re.VERBOSE 是不可协商的 - 这实际上是对巨大的多行正则表达式的大规模简化,其中 re.VERBOSE 是必要的,只是为了保持理智。)

import re
re.match(r'''Issue Summary.*''', 'Issue Summary: fails''', re.U|re.VERBOSE)
# No match!
re.match(r'''Issue Summary.*''', 'Issue Summary: passes''', re.U)
<_sre.SRE_Match object at 0x10ba36030>
re.match(r'Issue Summary.*', 'Issue Summary: passes''', re.U)
<_sre.SRE_Match object at 0x10b98ff38>
Run Code Online (Sandbox Code Playgroud)

是否有更明智的替代方案来编写包含有意义空格的 re.VERBOSE 友好模式,而不是用“\s”或“.”替换我的模式中的每个实例,这不仅丑陋而且违反直觉并且自动化很痛苦?

re.match(r'Issue\sSummary.*''', 'Issue Summary: fails', re.VERBOSE)
<_sre.SRE_Match object at 0x10ba36030>
re.match(r'Issue.Summary.*''', 'Issue Summary: fails', re.VERBOSE)
<_sre.SRE_Match object at 0x10b98ff38>
Run Code Online (Sandbox Code Playgroud)

(顺便说一句,这是 Python 2 和 3 上的一个有用的 docbug 捕获。一旦我在此处就正确的解决方案达成共识,我就会将其归档)

python regex flags whitespace

6
推荐指数
1
解决办法
903
查看次数

标签 统计

python ×3

regex ×2

flags ×1

multiline ×1

multilinestring ×1

string ×1

whitespace ×1