Skip to content Skip to sidebar Skip to footer

How To Find Substring In Python String

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 le

Solution 1:

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 hadtotal=20 cars
On thursday we hadtotal=20 cars
On wendesday we are going to havetotal=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).

Post a Comment for "How To Find Substring In Python String"