Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return None
#1
I am a beginner at programming and I wrote a function that returns the int value of a string but I want the function to return none if the input does not look like a number.

For example:

>>> casual_number("251")
251
>>> casual_number("1,aba,251")
>>> casual_number("1,251")
1251

Here is my code:
def casual_number(s):
    s=s.replace(',', '')
    return int(s)
What do I add to my code to do this??
Reply
#2
>>> str.isdigit('96985884')
True
>>> str.isdigit('969858f4')
False
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Thank you :)
Reply
#4
>>> '969858f4'.isdigit()
False
>>> '96985864'.isdigit()
True
Consider that this is the same. Any string is type str so both are identical
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
(Oct-07-2017, 11:22 PM)student8 Wrote: Thank you :)
Hi, I'm trying to do the same exercise but when I do casual_number("-,,,,"), it gives me an error. Can you please help me.
Thank you
Reply
#6
Put a print() to see what is in the string after replacing the comas. What you get is '-' and that can't be converted into an integer.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
(Oct-15-2017, 05:00 AM)sakssouk Wrote:
(Oct-07-2017, 11:22 PM)student8 Wrote: Thank you :)
Hi, I'm trying to do the same exercise but when I do casual_number("-,,,,"), it gives me an error. Can you please help me.
Thank you

Did you use the s.isdigit method for strings??
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020