how do you get code to count numbers of string
how do you get code to count how many numbers are in a string
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)
Boss68
@ash15khng you could also do
string = "abcdef54w6ed7fuyigy86giug75r54f789yu9ou2j89wrhg" # random string
counter = 0
for char in string:
if char in '0123456789':
counter += 1
print(counter)
KatieSchaefer
@ash15khng Why can't you just use len?
len(string)
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.
KatieSchaefer
@ash15khng Got it.
desond
asd
rsdud
Here is another way to do it in Python:
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 :
Here is another way to do it, using the isnumeric method, as well as map and sum.
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:
The regular expression '[^0-9]' means every character but a digit. All these characters are replaced by the empty string '' (or "" if you prefer).