Nick
Nick

Reputation: 21

Find inside a string in Python

There is a string, it contains numbers and characters.
I need to find an entire number(s) (in that string) that contains number 467033. e.g. 1.467033777777777

Thanks

Upvotes: 2

Views: 1306

Answers (3)

samplebias
samplebias

Reputation: 37929

Try this:

import re

RE_NUM = re.compile('(\d*\.\d+)', re.M)

text = 'eghwodugo83o135.13508yegn1.4670337777777773u87208t'
for num in RE_NUM.findall(text):
    if '467033' in num:
        print num

Prints:

1.4670337777777773

Generalized / optimized in response to comment:

def find(text, numbers):
    pattern = '|'.join('[\d.]*%s[\d.]*' % n for n in numbers)
    re_num = re.compile(pattern, re.M)
    return [m.group() for m in re_num.finditer(text)]

print find(text, ['467033', '13'])

Prints:

['135.13508', '1.4670337777777773']

Upvotes: 2

highBandWidth
highBandWidth

Reputation: 17316

import re
a = 'e.g. 1.467033777777777\nand also 576575567467033546.90 Thanks '
r = re.compile('[0-9.]*467033[0-9.]*')
r.findall(a)
['1.467033777777777', '576575567467033546.90']

Upvotes: 1

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56418

If you're just searching for a substring within another substring, you can use in:

>>> sub_num = "467033"
>>> my_num = "1.467033777777777"
>>> sub_num in my_num
True

However, I suspect there's more to your problem than just searching strings, and that doing it this way might not be optimal. Can you be more specific about what you're trying to do?

Upvotes: 1

Related Questions