Seán Dempsey
Seán Dempsey

Reputation: 105

Extract numeric values from a string for python

I have a string with contains numeric values which are inside quotes. I need to remove numeric values from these and also the [ and ]

sample string: texts = ['13007807', '13007779']

texts = ['13007807', '13007779'] 
texts.replace("'", "")
texts..strip("'")

print texts 

# this will return ['13007807', '13007779']

So what i need to extract from string is:

13007807
13007779

Upvotes: 0

Views: 160

Answers (3)

mad_
mad_

Reputation: 8273

The easiest way is to use map and wrap around in list

list(map(int,texts))

Output

[13007807, 13007779]

If your input data is of format data = "['13007807', '13007779']" then

import re
data = "['13007807', '13007779']"
list(map(int, re.findall('(\d+)',data)))

or

list(map(int, eval(data)))

Upvotes: 0

ncica
ncica

Reputation: 7206

You can use * unpack operator:

texts = ['13007807', '13007779']
print (*texts)

output:

13007807 13007779

if you have :

data = "['13007807', '13007779']"
print (*eval(data))

output:

13007807 13007779

Upvotes: 1

Youcef4k
Youcef4k

Reputation: 396

If your texts variable is a string as I understood from your reply, then you can use Regular expressions:

import re
text = "['13007807', '13007779']"
regex=r"\['(\d+)', '(\d+)'\]"
values=re.search(regex, text)
if values:
    value1=int(values.group(1))
    value2=int(values.group(2))

output:

value1=13007807

value2=13007779

Upvotes: 1

Related Questions