Can I specify regex group to return float or int instead of string?

J

Jeremy

I have a regular expression that searches for some numbers and puts
them into a dictionary, i.e.

'(?P<integer>\d+)\s+(?P<float>\d+\.\d+)'

Is it possible to have the results of the matches returned as int or
float objects instead of strings?

Thanks,
Jeremy
 
S

Steven D'Aprano

I have a regular expression that searches for some numbers and puts them
into a dictionary, i.e.

'(?P<integer>\d+)\s+(?P<float>\d+\.\d+)'

Is it possible to have the results of the matches returned as int or
float objects instead of strings?

No. Just convert the match with int() or float() before storing it in the
dictionary. That is, instead of:

d[key] = match

use

d[key] = float(match)

or similar.
 
J

Jeremy

I have a regular expression that searches for some numbers and puts them
into a dictionary, i.e.

Is it possible to have the results of the matches returned as int or
float objects instead of strings?

No. Just convert the match with int() or float() before storing it in the
dictionary. That is, instead of:

d[key] = match

use

d[key] = float(match)

or similar.

I was afraid that was the only option. Oh well, thought I'd ask
anyway. Thanks for your help.
Jeremy
 
S

Steven D'Aprano

I have a regular expression that searches for some numbers and puts
them into a dictionary, i.e.

Is it possible to have the results of the matches returned as int or
float objects instead of strings?

No. Just convert the match with int() or float() before storing it in
the dictionary. That is, instead of:

d[key] = match

use

d[key] = float(match)

or similar.

I was afraid that was the only option. Oh well, thought I'd ask anyway.


Why "afraid"? What's the problem with calling int or float on the match?
 
N

nn

On Thu, 25 Feb 2010 07:48:44 -0800, Jeremy wrote:
I have a regular expression that searches for some numbers and puts
them into a dictionary, i.e.
'(?P<integer>\d+)\s+(?P<float>\d+\.\d+)'
Is it possible to have the results of the matches returned as int or
float objects instead of strings?
No. Just convert the match with int() or float() before storing it in
the dictionary. That is, instead of:
d[key] = match
use
d[key] = float(match)
or similar.
I was afraid that was the only option.  Oh well, thought I'd ask anyway.

Why "afraid"? What's the problem with calling int or float on the match?

He must not be Dutch

:) SCNR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top