Python: Convert a string to an integer

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

    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
    

提交回复
热议问题