count_digits: (str) -> int Return the total number of characters in the given string that are digits. can anybody help me come up with a python code for this problem?
I don't know if I get the question right, but for the number of characters just an "x = str(raw_input('ask: '))" and a "for" loop with an increasing variable.
i need to count the number of digits within the string ignoring regular characters so if i wrote the word as kdfisfosdu32432 only the 32432 should be counted resulting in the answer 5 (as number of digits)
Sorry for delay, should be something like this then?? x = raw_input("ingresa algo: ") ans = 0 for i in x: if (i == '0'): ans += 1 elif (i == '1'): ans += 1 elif (i == '2'): ans += 1 elif (i == '3'): ans += 1 elif (i == '4'): ans += 1 elif (i == '5'): ans += 1 elif (i == '6'): ans += 1 elif (i == '7'): ans += 1 elif (i == '8'): ans += 1 elif (i == '9'): ans += 1 print ans Is kinda rough, I'll try to make it simpler
Going through it, I don't know how to make it simpler xD
i dont think i can use that
its too much aha
hahaha it's kinda annoying I know, but you can make it a function :P
i made this def count_digits(word): count = 0 for i in str(word): if i.isdigit(): count +=1 print (count) my only problem is say i do count_digits(ds23) instead of saying there is 2 digits it says count_digits(ds23) Traceback (most recent call last): File "<pyshell#81>", line 1, in <module> count_digits(ds23) NameError: name 'ds23' is not defined
what can i do to fix that so i can put letters and numbers in the sam thing and the code will just register the count of numbers
i know i have to make my variable word be a definitive string but how would i go about doing that?
Have you made the function "isdigit()" ?? if is made you should do something like: if i == isdigit(i)
Have you put any single quotes around 'ds23'?
All are treated as strings, that's why you can't make something simple like this: for i in x: if type(i) == int: ans += 1
you could do this def count_digits(word): count = 0 for c in word: for i in range(0,10): if str(i)==c: count +=1 print (count)
msmithhnova the idea was without and "str()" xD
Join our real-time social learning platform and learn together with your friends!