0

this is my code:

str_list = 'Hallo Welt Halloer' 
conversations_counter = len(re.findall("Hallo", str_list))
print(conversations_counter)

The result is 2! But I just want to have a match for the whole word 'Hallo'. The word 'Hallo' in the word 'Halloer' should not be counted.

Hallo = Hallo -> 1 Halloer <> Hallo -> 0

How to achieve this?

Thanks

HansMuff
  • 299
  • 1
  • 8
  • 22
  • I don't get the requirement. If you already know you are looking for the word `Hallo`, which has 5 characters, then why do you even need this script? – Tim Biegeleisen Jan 04 '23 at 13:46
  • @TimBiegeleisen I belies they are looking to count the occurrences of the word rather than the string which they are counting now. Not the number of characters in the word/string – JonSG Jan 04 '23 at 13:48

1 Answers1

1

Add a 'word boundary' to your regex:

Hallo\b

Don't forget to set the regex using r, not as string:

import re

str_list = 'Hallo Welt Halloer' 
conversations_counter = len(re.findall(r"Hallo\b", str_list))
print(conversations_counter) # 1

Try it online!

0stone0
  • 34,288
  • 4
  • 39
  • 64