In the following program, why is the count function failing? I'M getting an error that it needs at leat one argument and that I have given it 0. I have here count(number), how is number no an argument? According to the documentation the start and end points are optional. I figured that just giving one argument, the whole string, would give me the count on the whole thing by default and thats what the documentation suggested to me.

#!/usr/bin/python3
import sys

while(str.isdigit(sys.argv[1]) == True):
    number = sys.argv[1]
    print(number)
    print(str.count(str(number)))
    exit

print("Input was not a number ", "formate as this -> ", sys.argv[0], " 123")

Recommended Answers

All 6 Replies

Do not use str for a string variable name

print(str.count(str(number))) So how would I get this line done. when I write it as

print(str.count(number)) I get the same result.

str.count() example:

>>> "abracadabra".count("ab")
2
>>> 

This works ...

s = '1234567897'
number = 7
print(s.count(str(number)))

'''
2
'''

This gives you an error since str variable name interferes with str() function name ...

str = '1234567897'
number = 7
print(str.count(str(number)))

'''
TypeError: 'str' object is not callable
'''

Okay, I exited the code and it's no longer giving me an error but it is giving me output that doesn't make sence to me. It's printing "1" for the line print(number.count(str(number))) when has far as I can tell it should be printing 3.

garrett@garrett-bedroom ~/Projects/Enrique/NumbersToStrings/python $ ./NumbersToStrings.py 123
123
1

What I'm trying to do here is get the count the number of characters in number.

Here's the new code.

#!/usr/bin/python3
import sys

if(str.isdigit(sys.argv[1]) == True):
    number = sys.argv[1]
    print(number)
    print(number.count(str(number)))
else:
    print("Input was not a number ", "formate as -> ", sys.argv[0], " 123")
#!/usr/bin/python3
import sys

if(str.isdigit(sys.argv[1]) == True):
    number = sys.argv[1]
    print(number)
    #print(number.count(str(number)))
    print(len(str(number)))
else:
    print("Input was not a number ", "formate as -> ", sys.argv[0], " 123")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.