0

I want to return value without any error while casting string to integer.

For example, if I have a string "Hello World", it will return to false instead of error when I would like to use casting process.

This is error statement when I tried to casting string into int:

"ValueError: invalid literal for int() with base 10: 'From fairest creatures we desire increase,'"

string = int('From fairest creatures we desire increase,')

Dvyn Resh
  • 980
  • 1
  • 6
  • 14
  • Share your code – PySaad Aug 16 '19 at 10:19
  • Possible duplicate of [Is there a built-in or more Pythonic way to try to parse a string to an integer](https://stackoverflow.com/questions/2262333/is-there-a-built-in-or-more-pythonic-way-to-try-to-parse-a-string-to-an-integer) – Sweeper Aug 16 '19 at 10:21

3 Answers3

3

You could write a function for it.

def to_int(string):
    try:
        return int(string)
    except ValueError:
        return False

And call it like this:

>>> to_int("Hello World")
False
>>> to_int("10")
10

You could also add an optional Default value if you want to be more flexible

def to_int(string, default = False):
    try:
        return int(string)
    except ValueError:
        return default
Uli Sotschok
  • 1,206
  • 1
  • 9
  • 19
0

Strictly what you wanted but please read further:

def to_int(string):
    try:
        return int(string)
    except ValueError:
        return False

But in my opinion it should return None instead of False. Why? Booleans can be treated as ints [sic]:

>>> True + True
2
>>> False + False
2
>>> True < 2
True
>>> False < 2
True
>>> True + 1
2
>>> False + 1
1

etc.

So I recommend using:

def to_int(string):
    try:
        return int(string)
    except ValueError:
        return None

It will help you avoid some strange bugs, not mentioning that it simply sounds better.

Return False when there's a complimentary case when True can be returned as well. If not, return a valid value or None when it's not possible.

asikorski
  • 882
  • 6
  • 20
-2
def fun(str):
    if str.isdigit():
        return int(str)
    else:
        return False

this function will return int value if whole string is digit otherwise it will return False

Vashdev Heerani
  • 660
  • 7
  • 21
  • 1
    Although this will work it is not very pythotic, because it is against the [EAFP](https://stackoverflow.com/a/11360880/8411228) rule – Uli Sotschok Aug 16 '19 at 10:27
  • 2
    No no no no no. Never Look Before You Leap. If you try this with `'²'` it'll crash. – Aran-Fey Aug 16 '19 at 10:28
  • @Aran-Fey: nice one, didn't know `'²'` is considered a digit. Isn't it weird that it's a digit but it cannot build a valid number? – asikorski Aug 19 '19 at 07:08