1

I've got a string and I'd like to find and replace some numbers in it. I.e., there are multiple repetitions of "v = 324\n" in there, with different values. Now I want to divide all those numbers by n (rounded to nearest integer) and save it as a new string.

At the moment I'm using parse package:

n = 10
s = "this is v = 2342\n and another v = 231\n and some stuff..."
for r in findall("v = {:d}\\n", s):
    print r

This gives me the list of Results, but I don't know how to make changes to the string. How can I do it?

1 Answer 1

3

You can pass a function to re.sub that takes your matched pattern samples = {:d}\\n (which I had to update) and computes it in some way. Here is a demo:

import re

def sampleRounder(match):
    return str(int(float(match.group(1)))) #base=10

s = "this is v = 2342.2\n and another v = 231.003\n and some stuff..."

print(re.sub("v = ([0-9]*\.[0-9]+|[0-9]+)\\n", sampleRounder, s))
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Thank you, great answer and easy to reuse :)
This truncates instead of rounding to the nearest int, but as long as the OP can figure out how to to do that himself (hint: the round builtin does what it says, try help(round) for more), this should be all he needs.
I reread the OP's question and I can see that my sample code was way off of the request. I'll fix it when I get back to a desktop browser, but the idea still holds :)

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.