I'm trying to count the numbers of letters and numbers of a list. For example I want to get 15 letters and 5 numbers. I have a problem because I got the result but when i use debugger I see that for 5 function skips option with isdigit() and goes to isaplha(). What is the reason of this? The second problem is that I got for example 2 numbers as a ten but i want to get only 1. How to rebuild this code?
def coutning(list):
a= 0
b = 0
for elem in list:
for symbol in elem:
if elem.isdigit():
a =1
if symbol.isalpha():
b =1
return f' There is {a} numbers and {b} letters'
print(coutning(["1","7","8","9","10", "Hello my 543 friends"]))
CodePudding user response:
You need to move the if elem.isdigit():
condition before the second loop, and put the second loop in else:
. Thus, you first check if the element is displaying a number, and if not, then you count the letters in it.
def coutning(list):
a = 0
b = 0
for elem in list:
if elem.isdigit():
a = 1
else:
for symbol in elem:
if symbol.isalpha():
b = 1
return f' There is {a} numbers and {b} letters'
print(coutning(["1", "7", "8", "9", "10", "Hello my 543 friends"]))
Prints:
There is 5 numbers and 14 letters
If you want to count all numbers and letters as symbols, you can do it so:
def coutning(list):
a,b = 0,0
for elem in ''.join(list):
a = elem.isdigit()
b = elem.isalpha()
return f' There is {a} numbers and {b} letters'
print(coutning(["1", "7", "8", "9", "10", "Hello my 543 friends"]))
Output:
There is 9 numbers and 14 letters
CodePudding user response:
For everyone, I'm so sorry that you didn't understand what I mean. I said that in this code everything is okay until I reach numbers ( 543). When I reach it, I saw in debugger that I got 5, but the code skips isdigit and goes to isalpha. I think that 5 is not alpha, but it works in this way.
def coutning(list):
a= 0
b = 0
for elem in list:
for symbol in elem:
if elem.isdigit():
a =1
if symbol.isalpha():
b =1
return f' There is {a} numbers and {b} letters'
print(coutning(["1","7","8","9","10", "Hello my 543 friends"]))