Ashish Kumar
Ashish Kumar

Reputation: 17

python regex to count number of lines in a string which has only one specific word

I want to find the number of times a given string is the lone word on a line in my string. For example, if the word was "max" and the string was:

str = """max
     hello max
     max hi
     max"""

The correct output would be 2.

I tried using the re.findall function:

from re import findall
findall(r'^\max\n', str)

But it only counted one occurrence of "max":

['max\n']

Upvotes: 0

Views: 521

Answers (4)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

string = """max
     hello max
     max hi
     max"""
word='max'
print(sum([1 for elem in string.split('\n') if (word == elem.strip())]))

You can also try this

Upvotes: 0

Toto
Toto

Reputation: 91518

This does the job:

import re

str = """max max
     hello max
      max
      max
      max
      max
     max hi
     max"""


res = re.findall(r"(?m)^\s*max\s*$", str)
print res
print len(res)

Output:

['      max', '      max', '      max', '      max', '     max']
5

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

You can try this:

import re

str = """max
  hello max
  max hi
  max"""

results = len(re.findall("^max|max$", str))

Output:

2

Upvotes: 0

Chris
Chris

Reputation: 22993

You can use the sum builtin function:

>>> string = \
"""max
hello max
max hi
max"""
>>> sum('max' == line.strip() for line in string.split('\n'))
2

The above code works by adding up the number of times the string max is equal to the current line in string. The sum will be the number of times max appears by itself on a line.

Upvotes: 1

Related Questions