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?
=-sign intotal = XXX". Makes your question easier to understand with a fraction of the text.some_sentence = "We will use this sentence to get total=20 of cars."no matter if it has blank spaces before and after equal sign. And then add it in every string in list of string instead oftotal = <value>ortotal=<value>total = XXXfrom a sentence, and then insert the extracted value into the other sentences? I get it now. But your question is horribly unclear IMO. You should try to clarify it. (As in, in the question itself, not in the comments.)