Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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.

like image 827
Takkun Avatar asked Jun 17 '11 19:06

Takkun


People also ask

How do you extract numbers from a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.

How do you grab part of a string in Python?

You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end. You can also use negative values. If start > end , no error is raised and an empty character '' is extracted.

How do I print a number between strings in Python?

Method #2: Using %d operator This operator can be used to format the string to add the integer. The “d” represents that the datatype to be inserted to string is an integer.


2 Answers

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')]
like image 199
Roman Bodnarchuk Avatar answered Oct 01 '22 22:10

Roman Bodnarchuk


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)    
like image 21
Tudor Constantin Avatar answered Oct 01 '22 20:10

Tudor Constantin