+ 3
How do i find the total number of numbers in a string?
So I want to take user input and see how many numbers are in the string. How can I do that with python?
16 Answers
+ 8
JT JT , I suggest isdigit function or match the numbers in the string with regex. Look at my example. Hope it helps you.
https://code.sololearn.com/ch0z6bjHpAAH/?ref=app
+ 13
Muhammad Atif Waheed , there is no string method "isnum()" in python. The use of isdigit() is the best choice. isnumeric() does also recognize numerical representations from other languages, but this is not necessary.
+ 8
One-liner with a list comprehension.
print(len([x for x in input() if x.isdigit()]))
Also Zero if i.isdigit() would work. No need for the == True part. It is like writing if True. Great answer by the way 👌👌
Happy Coding 😀
+ 6
If there are only digits in input, you can use len(your_input) as already mentioned. But this means that that input can not be converted to int directly with input. If there are also other characters like letters or spaces, a version with regex can be done like this:
import re
inp = '8this i7s the 1st t1me in 2020'
print(len(re.findall(r"\d", inp)))
# result is 8 digits found
+ 4
number = input("Enter: ")
count = 0
for i in number:
if i.isdigit()==True:
count +=1
print(count)
+ 3
Tomiwa Joseph yeah you right no need == True: part
Just a bad programming habit thanks for the correction
+ 2
TheWh¡teCat 🇧🇬 - I guess the regex would be r"\d+" as JT JT asked for numbers, but not digits.
But, let's see what he says.
+ 2
@vrintle I think I meant digits, basically if I have a string that's 12345, then I want output of 5 (5 digits in the string)
+ 1
Tomiwa Joseph can you explain that code to me a bit more?
+ 1
Use
length();
function
+ 1
Lothar thank you!
0
Use isnum func
0
Use isnum func in for loop....
0
Чэйф
0
VAMSI oh OK thanks!
0
Спасибо!!!, только я не помню этого вопроса.