3

Say, I want to change the string 'A = (x+2.)*(y+3.)-1'

to

'A = (x+2.0e0)*(y+3.0e0)-1.0e0'.

Every number like 2. or just 2 should be changed. How to do this?

Thanks a lot!

2
  • Define "number". What should be the result of replacing this string for example: 1.2.3 4.5 6,7.8,9.a.6.c.0e891.0? Commented Mar 23, 2012 at 22:02
  • format of "number" will either be 2. or 2 No 1.2.3 stuff will exist in the string. Thanks Commented Mar 23, 2012 at 22:04

2 Answers 2

6

Given the comment you wrote, this kind of regular expression should work:

import re

str = 'A = (x+2.)*(y+3.)-1'
print re.sub(r'(\d+)\.?',r'\1.0e0',str)

Output:

A = (x+2.0e0)*(y+3.0e0)-1.0e0

Explanation of regexp:

  • (...) - means capturing group, what you need to capture to reuse during replacement
  • \d - means any number, equivalent to [0-9]
  • + - means 1 or more occurance, equivalent to {1,}
  • \.? - means that we want either 0 or 1 dot. ? is equivalent to {0,1}

In replacement:

  • \1 - means that we want to take first captured group and insert it here
Sign up to request clarification or add additional context in comments.

1 Comment

Added some explanation of what's going on.
2

You're going to want to look at the re module. Specifically, re.sub(). Read through the entire documentation for that function. It can do some rather powerful things. Either that or something like a for match in re.findall() construct.

1 Comment

Thanks.I've tried that but I don't know how to pass the number to the substituted output. Like, I'm able to translate 'A = x*2 + y+3' into 'A = x*something + y+something' but I'm not able to make it know the 2 and 3...

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.