Question

I want this part of my code to count the number of spaces in a string, so far I have that covered, but now, I want the code to return 1 if there are no spaces in the string.

Code:

    string = string.count(" ")

    if string == 0:
        string = string.count(" ") + 1

    return string

I get the following error:

    AttributeError: 'int' object has no attribute 'count'

How do I fix this? Any help is appreciated.

Was it helpful?

Solution

You are overreading your variable string, try using a new variable:

spaces = string.count(" ")

if spaces == 0:
    spaces = string.count(" ") + 1

return string

OTHER TIPS

Since 0 is considered to be False in a boolean context, I would use or here:

>>> string = "a b c"
>>> space_count = string.count(" ") or 1
>>> space_count
2
>>> string = "abc"
>>> space_count = string.count(" ") or 1
>>> space_count
1
>>>

Don't use string as the name of a variable, because if you do that, you will be changing the type of string to an int. You can use a different variable:

n = string.count(" ")

if n == 0:
    n = string.count(" ") + 1
...

Remember that count() returns an int, so if you assign that integer result to string, it won't be a string anymore. Therefore you can't call the method count() on it.

As the variable already declared as string = string.count(" ") the type of "string" at the moment is already an integer which is obviously has not 'count' attribute.

To fix your code, you just return string = string + 1 instead of string = string.count(" ") + 1

Also, as Christian mentioned, it is a good practice don't use some name may be confusing reader as the variable name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top