How to use variables containing numbers in regular expression?

时间:2017-08-05 10:40:21

标签: python regex

I have this as my code:

motifSearch = ''
intMin = 15
intMax = 21
intlen = intMax - intMin
SD = "TTGACA"
PBN = "TATAAT"

fastaFile = open('testseq.fsa', 'r')
for line in fastaFile:
    if deviation == 0:
        motSearch = re.search(SD+'([A-Z|a-z]){'+intMin,intMax+'}('+PBN+')', line)
        if motSearch is not None:
            motifSearch = motSearch.group(0)
print(motifSearch)

I have to find a first signal that is SD, then jump {intMin,intMax} number of characters, and then find the second signal PBN. When I print this out I get: "TypeError: Can't convert 'int' object to str implicitly". What am I doing wrong?

1 个答案:

答案 0 :(得分:4)

Use string formatting.

regex = '{}([A-Z|a-z]){{},{}}({})'.format(SD, intMin, intMax, PBN)

motSearch = re.search(regex, line)

If your reusing variables or want something more readable you can also specify order this way...

regex = '{0}([A-Z|a-z]){{1},{2}}({3})'.format(SD, intMin, intMax, PBN)

Another example of string formatting to address string formatting issues (not sure how to get around the case of of using {} as you cannot escape them)

regex = '%s([A-Z|a-z]){%s,%s}(%s)' % (SD, intMin, intMax, PBN)