Skip to content
← Back to Community
how do you get code to count numbers of string
Profile icon
RobaLobDob

how do you get code to count how many numbers are in a string

Voters
Profile icon
DavidPhilit-Voi
Profile icon
MeyermooreFundo
Profile icon
girianshiido
Profile icon
RobaLobDob
Comments
hotnewtop
Profile icon
girianshiido

Here is another way to do it in Python:

my_string = input('Enter your string:') print(my_string.translate({i+48:57 for i in range(9)}).count('9'))

Basically, you convert all the digits from 0 to 8 in you string to nines and then count the nines. The small dictionary is just here to convert each digit from '0' (character number 48) to '8' (character number 56) to a '9' (character number 57). You can create this dictionary using the maketrans method :

tab = maketrans('012345678', '9'*9) my_string = input('Enter your string:') print(my_string.translate(tab).count('9'))

Here is another way to do it, using the isnumeric method, as well as map and sum.

my_string = input('Enter your string:') print(sum(map(lambda x:x.isnumeric(), my_string)))

map applies the function lambda x:x.isnumeric() -whose purpose is to take a string and returns True if x is a number- to each character of my_string.
sum adds all the True and False, considering them as 1s and 0s.

Finally, here is another way to do it using the powerful re module:

import re my_string = input('Enter your string:') print(len(re.sub('[^0-9]', '', my_string)))

The regular expression '[^0-9]' means every character but a digit. All these characters are replaced by the empty string '' (or "" if you prefer).

Profile icon
ash15khng

In what language do you want to do this? In Python you can use something like

string = "abcdef54w6ed7fuyigy86giug75r54f789yu9ou2j89wrhg" # random string counter = 0 for char in string: if char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or char == '5' or char == '6' or char == '7' or char == '8' or char == '9': counter += 1 print(counter)
Profile icon
Boss68

@ash15khng you could also do

string = "abcdef54w6ed7fuyigy86giug75r54f789yu9ou2j89wrhg" # random string
counter = 0
for char in string:
if char in '0123456789':
counter += 1
print(counter)

Profile icon
KatieSchaefer

@ash15khng Why can't you just use len?
len(string)

Profile icon
ash15khng

@Boss68 Yea, I somehow didn't think of that :P

Profile icon
ash15khng

@KatieSchaefer If you use len(string) you are basically assuming the entire string is a number, which may not be the case, as he said string, not int.

Profile icon
KatieSchaefer

@ash15khng Got it.

Profile icon
desond

asd
rsdud