Python: Convert a string to an integer

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

    import re
    int(re.sub(r'[^\d-]+', '', your_string))
    

    This will strip everything except for numbers and the "-" sign. If you can be sure that there won't be ever any excess characters except for whitespace, use gruszczy's method instead.

提交回复
热议问题