-2

So I want to count exactly the number of appearances of "100" in python. My example code:

a = " I love 1000 and 100 dollars."
b = a.count("100")
print(b)

The result is 2 but I just want it is 1.

2
[Finished in 0.1s]

Is there any basic tip for that? I'm just a beginner learn python.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141

2 Answers2

1
" I love 1000 and 100 dollars.".split().count('100')

FYI, below is a convenient and efficient way of counting every word.

from collections import Counter

Counter("I love 1000 and 100 dollars.".split())

# result: Counter({'I': 1, 'love': 1, '1000': 1, 'and': 1, '100': 1, 'dollars.': 1})
gdlmx
  • 6,479
  • 1
  • 21
  • 39
  • @ĐăngBùi wants to return 1. Without `split()` the result would be 2. – gdlmx Mar 05 '19 at 02:18
  • @davedwards, the OP was looking for `100` not `1000`. the results are different in this case – aydow Mar 05 '19 at 02:23
  • Strings are iterators (like lists) themselves already and just count would work the same way though. count('100') instead of count('1000') would obviously return 2 – Jereme Mar 05 '19 at 02:23
  • @davedwards sorry I made a typo, it should be `count('100')`. – gdlmx Mar 05 '19 at 02:23
  • I think @gdlmx show my sastisfied answer. However is there any way to count directly in `str` objects? – Đăng Bùi Mar 05 '19 at 02:33
  • If we use object `list` to count, I can count string like this `"I love"`. If I use `split()` , the result of `" I love 1000 and 100 dollars.".split().count('I love')` will be `0`. :( – Đăng Bùi Mar 05 '19 at 02:48
1

If you want to count substrings within the string, the Regular Expression module, re, would be useful:

import re
len(re.findall(r'\b100\b', a)) # prints 1

len returning the count of how many occurrences re.findall() finds, i.e. 1.

Replace the 100 with the specific substring you wish to count:

b = len(re.findall(r'\bI love\b', a))
>>> b
1

technique borrowed from this answer Find substring in string but only if whole words?