Python: Convert a string to an integer

后端 未结 8 2134
余生分开走
余生分开走 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 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!-)

提交回复
热议问题