Reputation: 17
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
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
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
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
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