Takkun
Takkun

Reputation: 8659

How to grab numbers in the middle of a string? (Python)

random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string

random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string

random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string

Within one string there are multiple lines. One of the lines is repeated but with different numbers each time. I was wondering how can I store the numbers in those lines. The numbers will always be in the same position in the line, but can be any number of digits.

Edit: The random strings could have numbers in them as well.

Upvotes: 8

Views: 2660

Answers (3)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

Use regular expressions:

>>> import re
>>> comp_re = re.compile('this is (\d+) the string (\d+) that, i need (\d+)')
>>> s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string

random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string

random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string
"""
>>> comp_re.findall(s)
[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]

Upvotes: 7

Sven Marnach
Sven Marnach

Reputation: 601709

Assuming s is the whole multiline string, you can use code like

my_list = []
for line in s.splitlines():
    ints = filter(str.isdigit, line.split())
    if ints:
          my_list.append(map(int, ints))

This will give you a list of lists, one list of integers for each line that contains integers. If you would rather like a single list of all numbers, use

my_list = [int(i) for line in s.splitlines()
           for i in filter(str.isdigit, line.split())]

Upvotes: 4

Tudor Constantin
Tudor Constantin

Reputation: 26861

By using regular expressions

import re
s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
"""
re.findall('this is (\d+) the string (\d+) that, i need (\d+)', s)    

Upvotes: 4

Related Questions