Ok ran into wall too much. Could use some help. Thank you
def code(text: str) -> str:
emp_str = ""
for m in text:
if m.isdigit(): # Picks the numbers from text.
emp_str = emp_str m
if 0 < len(emp_str) < 11:
return "Not enough numbers!"
if len(emp_str) > 11:
return "Too many numbers!"
else:
return emp_str
if __name__ == '__main__':
print(code(""))
print(code("123456789123456789"))"
print(code("ID code is: 49403136526"))
print(code("efs4 9 #4aw0h 3r 1a36g5j2!!6-"))
End result should be:
Not enough numbers!
Too many numbers!
49403136526
49403136526
But instead i get:
Not enough numbers!
Not enough numbers!
Not enough numbers!
It semi works if i change this part of the code len(emp_str) < 11: to if len(emp_str) < 0:
Result:
Too many numbers!
49403136526
49403136526
Edited what i ment was the results look like the first line print answer is missing i know that len("") is 0.
CodePudding user response:
Better to use re
, I think. Like this:
import re
def code2(text: str):
matches = re.findall("\\d", text)
num_digits = len(matches) if matches else 0
if 0 <= num_digits < 11:
return "Not enough numbers!"
if num_digits > 11:
return "Too many numbers!"
return "".join(matches)
CodePudding user response:
There are several things wrong: you return a message only when some character isdigit
. First loop over the text and then assess the number of digits. Also don't forget to check for 0 in condition if 0 <= len(s) < 11
. Try following code:
s = ''
for m in text:
if m.isdigit():
s = m
if 0 <= len(s) < 11:
return "Not enough numbers!"
elif len(s) >= 11:
return "Too many numbers!"
return s
CodePudding user response:
I've never had much luck with isdigit(). I use a try/except statement to accomplish this
def code(text: str) -> str:
emp_str = ""
for m in text:
try:
int_buffer = int(m). # try to make string into an integer
emp_str = emp_str m
if len(emp_str) > 11:
return "Too many numbers!"
if not len(emp_str):
return "Not enough numbers!"
except Value error:
pass
return emp_str
if __name__ == '__main__':
print(code(""))
print(code("123456789123456789"))"
print(code("ID code is: 49403136526"))
print(code("efs4 9 #4aw0h 3r 1a36g5j2!!6-"))