mastodon
mastodon

Reputation: 497

Split a string into multiple variables

I have a string in the following form :

"425x344"

Now I'd like to resolve first and second numbers from this string as two separate variables. How can I do this ? I've created this regex:

regex = re.compile(r"^(\d+x\d+)")

to check if the string form is proper. But what next ?

Upvotes: 0

Views: 1600

Answers (5)

aaronasterling
aaronasterling

Reputation: 70994

Since you're filtering it with a regex, you can just do

a, b = map(int, s.split('x'))
res = a * b

If you're planning on multiplying, it can be done in one line:

res = eval(s.replace('x', '*'))

or

res = (lambda x, y: x * y)(*map(int, s.split('x')))

With an import and one line, this can be done with

import operator

res = operator.mul(*map(int, s.split('x')))

You'll have to profile them to see which is faster.

Upvotes: 2

robbrit
robbrit

Reputation: 17960

Change it to:

regex = re.compile(r"^(\d+)x(\d+)")

Then use regex.match(my_string) to get the MatchObject out, and you can use match.group(1) and match.group(2) to get the variables out.

Upvotes: 1

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

If you are wanting to do it with re, http://effbot.org/zone/xml-scanner.htm might be worth a read. It shows how to properly split each argument in a expr with re

import re

expr = "b = 2 + a*10"

for item in re.findall("\s*(?:(\d+)|(\w+)|(.))", expr):
    print item

Upvotes: 0

unwind
unwind

Reputation: 399753

You probably mean "values", or "literals". 425 is not typically a valid name for a variable, which tend to have symbolic names.

If you change your regular expression to capture the numbers separately:

regex = re.compile(r"^(\d+)x(\d+)")

you can then use code like this:

str = "425x344"
mo = regex.search(str)
if mo != None:
  print "%s=%d" % (str, int(mo.group(1)) * int(mo.group(2)))

to compute the result.

Upvotes: 0

Simone
Simone

Reputation: 11797

a, b = '425x344'.split('x')

Upvotes: 5

Related Questions