使用.format在正则表达式findall对象中使用变量。蟒蛇 [英] Using .format to use variable in regex findall object. Python
问题描述
我看到这里的一些例子,但它没有回答我的问题:
正则表达式findall与变量
我试图使用一个变量,而不是9,但我似乎无法弄清楚
value = 9
ORF = re.findall(r'ATG(?:( ?! TAA | TAG | TGA )...){value,}?(?:TAA | TAG | TGA)',seq)
#显然不起作用,或者我不会发这篇文章
$ b我试过:
$ p $value = 9
ORF = re.findall('TAA | TAG | TGA)...){{},}?
但遇到错误:
<$ p $在$格式字符串中遇到单个'}'
:
value = r'{}'。格式(9)
ORF = re.findall(r'ATG (:( ?! TAA?| TAG | TGA)...){VAL ue,}?(?:TAA | TAG | TGA),seq)
但是当我向下游看时,它并没有工作。
我怎么能得到这个变量在我的正则表达式?
$ Python是抱怨,有其他 {
和} / code>在你的字符串中没有用于格式化,而且它不知道如何区分它们。在一个格式化字符串中,花括号加倍。
您还需要转义值中的任何正则表达式字符
所以也许:
pre $ ORF = re.findall(
r'ATG(?:(?!TAA | TAG | TGA)...){{{},}}?(?:TAA | TAG | TGA)'
.format(re.escape值)),
seq)
在这样的情况下,会错过你使用%
-formatting或旧的字符串连接:)
I saw some examples of this here but it did not answer my question: Python Regular Expression findall with variable
i'm trying to use a variable instead of the 9 but i can't seem to figure it out
value = 9
ORF = re.findall(r'ATG(?:(?!TAA|TAG|TGA)…){ value ,}?(?:TAA|TAG|TGA)',seq)
#obviously doesn't work or i wouldn't have made this post
I tried:
value = 9
ORF = re.findall(r'ATG(?:(?!TAA|TAG|TGA)…){ {} ,}?(?:TAA|TAG|TGA)'.format(value),seq)
but got the error:
ValueError: Single '}' encountered in format string
then I tried:
value = r'{}'.format(9)
ORF = re.findall(r'ATG(?:(?!TAA|TAG|TGA)...){value,}?(?:TAA|TAG|TGA)',seq)
and got no error but it didn't work when i looked downstream
How can I get this variable to work in my regular expression?
Python is complaining that there are other {
and }
in your string not used for format, and it doesn't know how to tell the difference. In a format string, braces are escaped by doubling them.
You also need to escape any regex characters in your value
.
So perhaps:
ORF = re.findall(
r'ATG(?:(?!TAA|TAG|TGA)…){{{},}}?(?:TAA|TAG|TGA)'
.format(re.escape(value)),
seq)
In a case like this, though, I doubt anyone would fault you for using %
-formatting or good old string concatenation instead :)
这篇关于使用.format在正则表达式findall对象中使用变量。蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!