-2

I was wondering if in python it would be possible to extract certain integers from a variable and save it as a seperate variable for later use.

for example:

str1 = "numberone=1,numbertwo=2,numberthree=3"

newnum1 = [find first integer from str1]

newnum2 = [find second integer from str1]

answer = newnum1 * newnum2

print(answer)
3
  • what is your input look like??? Commented Dec 2, 2014 at 16:42
  • Yes, you can certainly parse the string to extract what you want. Commented Dec 2, 2014 at 16:42
  • Check stackoverflow.com/questions/11339210/…, try something, if you fail, show what you have tried Commented Dec 2, 2014 at 16:42

3 Answers 3

1

Try findall:

num1, num2, num3 = re.findall(r'\d+', 'numberone=1,'
                                      'numbertwo=2,'
                                      'numberthree=3')

Now num1 contains the string 1, num2 contains 2, num3 contains 3.

If you want only two numbers (thanks to @dawg), you can simply use the slice operator:

num1, num2=re.findall(r'\d+', the_str)[0:2]
Sign up to request clarification or add additional context in comments.

1 Comment

Since he is only looking for two numbers, you might consider: num1, num2=re.findall(r'\d+', the_str)[0:2]
1

You have some choice for this :

using str.split() :

>>> [int(i.split('=')[1]) for i in str1.split(',')]
[1, 2, 3]

using regular expressions :

>>> map(int,re.findall(r'\d',str1))
[1, 2, 3]

Comments

0
(?<==)\d+(?=,|$)

Try this.See demo.

http://regex101.com/r/yR3mM3/19

import re
p = re.compile(ur'(?<==)\d+(?=,|$)', re.MULTILINE | re.IGNORECASE)
test_str = u"numberone=1,numbertwo=2,numberthree=3"

re.findall(p, test_str)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.