toofly
toofly

Reputation: 2307

Python: how to grab a substrings when the indices are dynamic

I am working with many lines in a file, in which I want to retrieve a certain element which may be of varying length, and is not flanked consistently by the same characters.

Here's an example. I want to retrieve the item that starts with "OOO_" on each line:

blah blah OOO_128934( blah blah
blah bloop OOO_231 bloop bloop
beep OOO_421398234beep beep

Solutions with/without using the re module are appreciated!

Upvotes: 0

Views: 1192

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

Then maybe:

text = """
blah blah OOO_128934( blah blah
blah bloop OOO_231 bloop bloop
beep OOO_421398234beep beep
"""

import re

print re.findall(r'OOO_\d+', text) 
>>> ['OOO_128934', 'OOO_231', 'OOO_421398234']

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 602635

>>> s = "blah bloop OOO_231 bloop bloop"
>>> next(x for x in s.split() if x.startswith("OOO_"))
'OOO_231'

Upvotes: 1

Related Questions