1

i need to count how many periods (points) appear in a string.

for example:

str="hellow.my.word."

the code should return 3.

I tried to use the following function but it returns the length of the string.

 num=str.count('.')

What is the correct way to do it?

yaron0
  • 57
  • 1
  • 4
  • Other answers that I have seen appear to use iterations. Using iterations is not appropriate for this purpose. Use regular expressions instead: `len(re.findall("(\.)", my_string))` – Pouria May 08 '16 at 14:17

3 Answers3

2

Use variable name other than str(str is built-in).

Secondly:

string = "hellow.my.word."
num=string.count('.') # num=3 ...THIS WORKS
SivNiz
  • 108
  • 3
1

Use a for comprehension to iterate over the string:

Also, don't use str as a variable name, it's a built-in function in python.

string="hellow.my.word."

sum([char == '.' for char in string])  # Returns 3

EDIT

Regarding @niemmi's comment, apparently this is possible using string.count('symbol'):

string.count('.') # returns 3

Docs: https://docs.python.org/2/library/string.html#string.count

Anthony E
  • 11,072
  • 2
  • 24
  • 44
  • FWIW, although `str` is certainly a callable it's not really a function. `str` is a type (IOW, a class), so when you call it it creates a new string instance. – PM 2Ring May 08 '16 at 16:25
1

One possible solution is to filter out other characters than . and measure the length of resulting list:

len([1 for c in string if c == '.'])
enedil
  • 1,605
  • 4
  • 18
  • 34