1

Objective: to find digits that start at the beginning of a sentence and change the number in place to equal the original number plus 10%.

msg_orginal = """Hello, I am new here. 
2,431 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,428.5 would then be new."""

The output I am seeking is as follows:

msg_revised = """Hello, I am new here. 
2,674.1 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,671.35 would then be new."""

Notice how two of the three sentences have changed the numerical values, but one did not.

EDIT: Keep in mind the same number could appear multiple times in the string. And a new sentence is a sentence that comes either after a full stop (such as a period, exclamation mark, question mark) or that comes after a new line character.

Student
  • 1,197
  • 4
  • 22
  • 39

2 Answers2

2

You can use re.sub with a regex like r"^[\d,.]+" using the multiline-flag re.M so that ^ matches a line break and a replacement function for doing the math and formatting the output:

>>> increase = lambda m: "{:,.2f}".format(float(m.group().replace(",","")) * 1.1)

>>> print(re.sub(r"^[\d,.]+", increase, msg_orginal, flags=re.M))
Hello, I am new here. 
2,674.10 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,671.35 would then be new.

This assumes that all sentences start at a new line (and no sentences span more than one line) as is the case in your example. This problems (if itis a problem) can be handled separately.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0
msg_orginal = """Hello, I am new here. 
2,431 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,428.5 would then be new."""

res = []

for i in msg_orginal.split("\n"):
    if i[0].isdigit():
        val = i.split()
        f = float(val[0].replace(",", ""))
        val[0] = str((f/10.0) + f)
        res.append(" ".join(val))
    else:
        res.append(i)

print "\n".join(res)

Output:

Hello, I am new here. 
2674.1 other coders are new here too.
Imagine if 2.5 were not new here? 
2671.35 would then be new.
cs95
  • 379,657
  • 97
  • 704
  • 746
Rakesh
  • 81,458
  • 17
  • 76
  • 113