0

I have numeric strings in fortran format that look like this 0.1245-102 float conversion doesn't work because format is not expected : 0.1245e-102

I use this command

re.sub(r"[0-9]-[0-9]",r"e-","0.1245-102")

I 'm very new to regular expression and with this way i obtain 0.124e-02 how can i keep 5e-1 in new result ?

6
  • Why not simply '0.1245-102'.replace('-', 'e-')? Commented Apr 4, 2013 at 15:02
  • @PavelAnossov -- fails for negative numbers Commented Apr 4, 2013 at 15:02
  • @ANSWERERS -- Other ways which these numbers could possibly appear (I think): 1-10, 1.-10, -1-10 -- I think the accepted solution should handle these just in case ... Commented Apr 4, 2013 at 15:04
  • 1
    What do positive exponents look like? 1E10? 1+10? Commented Apr 4, 2013 at 15:05
  • 1
    'e-'.join('0.1245-102'.rsplit('-',1)) ? Commented Apr 4, 2013 at 15:07

1 Answer 1

3

You are looking for:

r'(?<=\d|\.)-(?=\d)'

which matches a - if there are digits or a dot) before, and digits after.

Demo:

>>> exponent = re.compile(r'(?<=\d|\.)-(?=\d)')
>>> exponent.sub('e-', '0.1245-102')
'0.1245e-102'
>>> float(exponent.sub('e-', '0.1245-102'))
1.245e-103
>>> float(exponent.sub('e-', '1-10'))
1e-10
>>> float(exponent.sub('e-', '1.-10'))
1e-10
>>> float(exponent.sub('e-', '-1-10'))
-1e-10

To handle both - and D+ (negative and positive exponents), you could use:

r'(?<=\d|\.)D?(?=(?:\+|-)\d)

which would allow for and replace an optional D, leaving the - or + in place when replacing:

>>> exponent = re.compile(r'(?<=\d|\.)D?(?=(?:\+|-)\d)')
>>> float(exponent.sub('e', '0.1245-102'))
1.245e-103
>>> float(exponent.sub('e', '456D+5'))
45600000.0

This does allow for the D to also precede the -, so 0.1245D-102 would be valid too, but it simplifies the replacement handling.

Sign up to request clarification or add additional context in comments.

6 Comments

yes it sounds like this . I forgot positives exponent look like this "456D+5"
yes but it fails for positif have i to include this call in a try - except test ? or is there other thing to do with compile function ?
What do your positive exponents look like? You can do a try: except: or first test if there is a match.
positives are for example "456D+5"
@froggy: So D+ needs to be replaced with e?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.