How do I add something after each number in a line in PYTHON?
Let's say I want to change the line "A = (x + 2. ) * (y + 3. ) - 1 '
to
'A = (x + 2.0e0 ) * (y + 3.0e0 ) - 1.0e0 '.
Every number like 2. or just 2 must be changed. How to do it?
Thank you so much!
+3
agent99
source
to share
2 answers
Given the comment you wrote, this regex 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
Regexp explanation:
-
(...)
- means a capture group that you need to capture for reuse during replacement -
\d
- means any number equivalent to [0-9] -
+
- means 1 or more events equivalent{1,}
-
\.?
- means we want either 0 or 1dot
.?
equivalent to{0,1}
Instead:
-
\1
- means that we want to take the first group of captured and insert it here
+6
bezmax
source
to share
You need to look at re
module . In particular, re.sub()
. Read all the documentation for this function. He can do some pretty powerful things. Either that or some kind of construct for match in re.findall()
.
+2
Kurt spindler
source
to share