agent99
agent99

Reputation: 75

How to add something after every number in a string in PYTHON?

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!

Upvotes: 3

Views: 284

Answers (2)

bezmax
bezmax

Reputation: 26132

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

Upvotes: 6

Kurt Spindler
Kurt Spindler

Reputation: 1321

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.

Upvotes: 2

Related Questions