我试图在Python中添加一个变量,并发现在.format(variable)
中使用像.format(variable)
这样的字符串格式是正常的,但现在我也想指定正则表达式的某些部分的长度,如下所示:
n = re.search(r"""(((\s|^) # Start with either whitespace or start of line
{0}) # String 'item'
\d{5,7} # 5-7 digits
\b) # End with word border
""".format(item), text, re.VERBOSE)
然后,正则表达式将长度{5,7}
的规范解释为对变量的引用,因为我得到了错误消息Key error: '5,7'
。
在将regex发送到re.search(regex, text)
之前,我让它将regex指定为变量,但我想对regex的不同部分进行注释,从而使用详细的格式。
我还尝试使用%s
和% item
进行字符串格式设置,但这给了我一个语法错误:
""", % item, transcription, re.VERBOSE)
^
SyntaxError: invalid syntax
我是否在代码中犯了任何错误,或者是否必须使用其他方法(如果有)?
发布于 2016-03-14 10:45:13
需要将需要保留为文本的大括号加倍(请参阅文档):
n = re.search(r"""(((\s|^) # Start with either whitespace or start of line
{0}) # String 'item'
\d{{5,7}} # 5-7 digits
\b) # End with word border
""".format(item), text, re.VERBOSE)
https://stackoverflow.com/questions/35985255
复制相似问题