halim hamadi halim hamadi - 4 days ago 4
Python Question

Get number from sentences python

How I can get data from sentences ?

for the example
I have this sentences

4 bedroom 2 bath, 1469 sq


then I have done search word 'bath' in the sentence, but from that sentence I want get number '2' because it was my data.

How I can put number '2' from that sentence ?

thank you

Answer

You may use a simple regex with capturing group:

import re
s= "3 roof 4 bath"
search_word = "bath"
res = re.search(r'(\d+)\s*{0}'.format(re.escape(search_word)), s)
if res:
    print(res.group(1))

See the Python demo

Details:

  • (\d+) - Group 1: one or more digits are captured into Group 1 (note: if the number can contain commas or periods, use [\d,.]+ instead of \d+, or a more precise \d+(?:[,.]\d+)*)
  • \s* - 0+ whitespaces
  • {0}' - a placeholder for the search word whose chars are escaped withre.escape()` in order to match even if there are special regex chars in it

To access the digits, use .group(1) on the match data object.

Comments