0

I need a code to choose between two characters within the same string.

Example:

I want to find acf('h' or 'n')atd in

'avhavaacfhatdvatyacyactycatycasacfnatdtycstyscaacfnatdtycsatycatycaycsa'
hydronium
  • 198
  • 3
  • 11
  • I would recommend using a regular expression for this. – Gabe Feb 10 '14 at 02:18
  • 2
    When you say "find", are you trying to find the index of either of those strings occurring? Also, your title and the body of your question are asking two different things. Please clarify which one you're actually asking about. – senshin Feb 10 '14 at 02:20
  • If you find the answer correct or useful, please accept :) – laike9m Feb 12 '14 at 08:57

2 Answers2

0

This is a problem which is solved using regular expressions. Try using findall from the re module:

import re

s = 'avhavaacfhatdvatyacyactycatycasacfnatdtycstyscaacfnatdtycsatycatycaycsa'
matches = re.findall('acf[hn]atd', s)
print matches

Output:

['acfhatd', 'acfnatd', 'acfnatd']
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
0

findall only returns all non-overlapping matches of pattern in string, as a list of strings. It doesn't contain inforamtion about position, which is probably what you want.

Try finditer instead, it returns an iterator yielding match objects, while match objects contain those info.

>>> import re
>>> s = 'avhavaacfhatdvatyacyactycatycasacfnatdtycstyscaacfnatdtycsatycatycaycsa'
>>> match_iter = re.finditer('acf[hn]atd', s)
>>> for match in match_iter:
        print("%s, start: %s, end: %s" % (match.group(), match.start(), match.end()))

acfhatd, start: 6, end: 13
acfnatd, start: 31, end: 38
acfnatd, start: 47, end: 54

The above code doesn't work if matched patterns overlap. To find all overlapping matches, see Python regex find all overlapping matches?.

For your question

>>> matcheobj = re.finditer(r'(?=(acf[hn]atd))', s)

Since your specific pattern definitly won't lead to overlapping, it makes no difference which form you use.

Community
  • 1
  • 1
laike9m
  • 18,344
  • 20
  • 107
  • 140