Python: Convert a string to an integer

后端 未结 8 1997
余生分开走
余生分开走 2020-12-07 01:22

Does anybody have a quickie for converting an unsafe string to an int?

The string typically comes back as: \'234\\r\\n\' or something like

相关标签:
8条回答
  • 2020-12-07 01:45

    Under Python 3.0 (IDLE) this worked nicely

    strObj = "234\r\n"
    try:
        #a=int(strObj)
    except ValueError:
        #a=-1

    print(a) >>234


    If you're dealing with input you cannot trust, you never should anyway, then it's a good idea to use try, except, pass blocks to control exceptions when users provide incompatible data. It might server you better to think about try, except, pass structures as defensive measures for protecting data compatibility rather than simply hidding errors.

    try:
        a=int(strObj) #user sets strObj="abc"
    except ValueError:
        a=-1

    if a != -1:
        #user submitted compatible data
    else:
        #inform user of their error

    I hope this helps.

    0 讨论(0)
  • 2020-12-07 01:46

    You could just:

    def to_int(unsafe_string):
        return int(unsafe_string.strip())
    

    But it will throw a ValueError if the stripped unsafe_string is not a valid number. You can of course catch the ValueError and do what you like with it.

    0 讨论(0)
  • 2020-12-07 01:56
    try:
        x=int("234\r\n".strip())
    except ValueError:
        x=0
    
    0 讨论(0)
  • 2020-12-07 02:01

    In this case you do have a way to avoid try/except, although I wouldn't recommend it (assuming your input string is named s, and you're in a function that must return something):

    xs = s.strip()
    if xs[0:1] in '+-': xs = xs[1:]
    if xs.isdigit(): return int(s)
    else: ...
    

    the ... part in the else is where you return whatever it is you want if, say, s was 'iamnotanumber', '23skidoo', empty, all-spaces, or the like.

    Unless a lot of your input strings are non-numbers, try/except is better:

    try: return int(s)
    except ValueError: ...
    

    you see the gain in conciseness, and in avoiding the fiddly string manipulation and test!-)

    I see many answers do int(s.strip()), but that's supererogatory: the stripping's not needed!

    >>> int('  23  ')
    23
    

    int knows enough to ignore leading and trailing whitespace all by itself!-)

    0 讨论(0)
  • 2020-12-07 02:01

    Without knowing what kinds of inputs you are expecting, it's hard to say what is 'enough' to solve this. If you are just worried about trailing newlines, then Xavier Combelle's or gruszczy's answer is enough:

    try:
        x = int(value)
    except ValueError:
        x = 0
    

    If you have to find any integer, anywhere in a string, then you might need something like this:

    import re
    try:
        x = int(re.search(r'(0|(-?[1-9][0-9]*))', searchstring).group(0))
    except TypeError: # Catch exception if re.search returns None
        x = 0
    
    0 讨论(0)
  • 2020-12-07 02:06

    int('243\r\n'.strip())

    But that won't help you, if something else than a number is passed. Always put try, except and catch ValueError.

    Anyway, this also works: int('243\n\r '), so maybe you don't even need strip.

    EDIT:

    Why don't you just write your own function, that will catch the exception and return a sane default and put into some utils module?

    0 讨论(0)
提交回复
热议问题