Reputation: 12084
I have an list of strings as follows:
strings = [
"On monday we had total=5 cars",
"On tuesday we had total = 15 cars",
"On wensdsday we are going to have total=9 or maybe less cars"
]
I want to be able to find and replace substring from those strings.
I can find and replace it as follows (If I have string with which I want to replace):
new_total = "total = 20"
for str in strings:
new_string = re.sub(r"total\s?=\s?5", "{}".format(new_total), str)
print(new_string)
In this case it matches only total=5
. This is not what I want.
I want first to extract the total = <value>
from a sentence, no matter if it has blank spaces before or after =
sign, and then insert the extracted value into the other sentences
Thus something as follows:
some_sentence = "We will use this sentence to get total=20 of cars."
new_total = "????" // it needs to get total=20
for str in strings:
// Here I want to replace `total=<value>` or `total = <value>` in every str with new_total
new_string = "????"
print(new_string)
The output should be:
"On monday we had total=20 cars",
"On tuesday we had total=20 cars",
"On wensdsday we are going to have total=20 or maybe less cars"
Any idea how can I do that?
Upvotes: 0
Views: 123
Reputation: 10782
You were almost there. Instead of your hardcoded 5
use \d+
in the regex:
import re
strings = [
"On monday we had total=5 cars",
"On thursday we had total = 15 cars",
"On wendesday we are going to have total=9 or maybe less cars"
]
new_total = "total = 20"
for s in strings:
new_string = re.sub(r"total\s?=\s?\d+", "{}".format(new_total), s)
print(new_string)
# to extract the information you can use:
p = re.compile(r"(total\s?=\s?\d+)")
for s in strings:
print( p.findall(s) )
Output:
On monday we had total = 20 cars
On thursday we had total = 20 cars
On wendesday we are going to have total = 20 or maybe less cars
['total=5']
['total = 15']
['total=9']
If you are sure you will have a match, you could also use p.search(s).group(0)
(which will return the string instead of a list) instead of p.findall(s)
.
Upvotes: 1