+ 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?

14th Nov 2020, 8:08 PM
JT JT
JT JT - avatar
16 Antworten
+ 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
14th Nov 2020, 8:29 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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.
14th Nov 2020, 9:14 PM
Lothar
Lothar - avatar
+ 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 😀
14th Nov 2020, 9:29 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 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
20th Nov 2020, 10:20 AM
Lothar
Lothar - avatar
+ 4
number = input("Enter: ") count = 0 for i in number: if i.isdigit()==True: count +=1 print(count)
14th Nov 2020, 8:53 PM
Zero
Zero - avatar
+ 3
Tomiwa Joseph yeah you right no need == True: part Just a bad programming habit thanks for the correction
14th Nov 2020, 9:32 PM
Zero
Zero - avatar
+ 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.
15th Nov 2020, 8:05 AM
777
777 - avatar
+ 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)
15th Nov 2020, 10:36 PM
JT JT
JT JT - avatar
+ 1
Tomiwa Joseph can you explain that code to me a bit more?
15th Nov 2020, 10:36 PM
JT JT
JT JT - avatar
+ 1
Use length(); function
16th Nov 2020, 3:49 PM
VAMSI
VAMSI - avatar
+ 1
Lothar thank you!
21st Nov 2020, 7:22 PM
JT JT
JT JT - avatar
0
Use isnum func
14th Nov 2020, 8:15 PM
Muhammad Atif Waheed
Muhammad Atif Waheed - avatar
0
Use isnum func in for loop....
14th Nov 2020, 8:15 PM
Muhammad Atif Waheed
Muhammad Atif Waheed - avatar
0
Чэйф
16th Nov 2020, 1:36 PM
nikolay
nikolay - avatar
0
VAMSI oh OK thanks!
17th Nov 2020, 1:39 AM
JT JT
JT JT - avatar
0
Спасибо!!!, только я не помню этого вопроса.
20th Nov 2020, 10:50 AM
nikolay
nikolay - avatar