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?

1
  • 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)) Commented May 8, 2016 at 14:17

3 Answers 3

2

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

Secondly:

string = "hellow.my.word."
num=string.count('.') # num=3 ...THIS WORKS
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.
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 == '.'])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.