0

For example I have a code like this

string = "abito to doto moto" 
print(string.count("to"))

I just want the result to be 1, but it always count "to" in the other three as well

4 Answers4

2

You might use regular expression (re module) following way:

import re
string = "abito to doto moto"
occurences = len(re.findall(r'\bto\b',string))
print(occurences)

Output:

1

Explanation: \b has special meaning in 1st argument of re.findall namely word boundary - meaning that there needs to be start of string or punctuation (including space) before to and end of string or or punctuation (including space) after to. So my code would give 1 also for string equal to abito to, doto moto or abito to: doto moto and so on.

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

I have ingored the first and last occurences of "to". you can change the condition in for loop as per your need.

li = list(string.split(" ")) 
count = 0;
for i in range(1,len(li)-1):
    if li[i]== "to":
        count= count + 1
print(count)
Vignesh_A
  • 508
  • 1
  • 7
  • 19
0

string.count(" to ") works only if there is no special characters after "to"

here's some examples:

    >>> string = 'abito to doto moto to.'
    >>> string.count("to")
    5
    >>> string.count(" to ")
    1
    >>> string.split().count("to")
    1
    >>> string.split(" ").count("to")
    2
    >>> import re
    >>> sum(1 for _ in re.finditer(r'\b%s\b' % re.escape("to"), string))
    2

Edit: Thank @Grzegorz Krug for suggest edit, this will give you result of 2 (since my string is different from @Jess example) when using regex:

how_many = len(re.findall('\Wto\W', string)) # '\W' is to avoid word symbols a-zA-Z and _

AcaNg
  • 704
  • 1
  • 9
  • 26
0

You have to add blanks to this string 'to' -> ' to ', which i don't recommend. Becouse it look like you want to find words 'to', and adding space may fails if string starts from 'to'

string = "abito to doto moto" 
words = string.split()
print(words.count("to"))
Grzegorz Krug
  • 186
  • 2
  • 11