2

I want to find all 2 word strings in python. I created this:

#!/usr/bin/python
import re

string='a1 a2 a3 a5 a6'
search=re.findall('.. ..',string)
print len(search)
for nk in search:
        print nk

I am getting: a1 a2 a3 a5 While I wanted:a1 a2,a2 a3,a3 a5,... etc The findall should search for all possible patterns? And why returns a1 a2,a3 a5? Thank you.

0

1 Answer 1

2

It returns ['a1 a2', 'a3 a5'], because these are the only patterns which can be found: after applying the first one, the 'a1 a2' part is gone and ' a3 a5 a6' is left. The next possible pattern is 'a3 a5', and ' a6' is left over and cannot be matched further.

'a1 a3', 'a1 a5' etc. cannot be found because this combinations don't occur. Remember, you search for two arbitrary characters, followed by a space character, followed by 2 arbitrary characters.

With

r=re.compile(r"(\S{2})(?:\s|$)")
pairs =r.findall("a1 a2 a3 a5 a6")

or

pairs = re.findall(r"(\S{2})(?:\s|$)", "a1 a2 a3 a5 a6")

you find all 2-character combination which are wither followed by a space or by the end of the string: ['a1', 'a2', 'a3', 'a5', 'a6']. If you combine these, you will find all possible combinations:

for ifirst in range(len(pairs) - 1):
    for second in pairs[ifirst + 1:]:
        print " ".join((pairs[ifirst], second))
Sign up to request clarification or add additional context in comments.

6 Comments

At first, I thought my monitor was dirty. Then I realized the h in "characters" had a caron.
If i want to find and a2-a3 is there any better way than running the search again on the original string without a1?
@NullUserException Thx for your regex; I added a r to make it a raw string and I added () for not finding the spaces after them. And thx for the caron hint :-)
@nikosdi Either that or you re-assemble the pair of pairs :-) again afterwards as shown in the example.
Or items = 'a1 a2 a3 a5 a6'.split();['%s %s' % x for x in zip(items, items[1:])]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.