Python: Convert a string to an integer

后端 未结 8 1998
余生分开走
余生分开走 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:06
    def str_to_int(a):
        str_to_int_output=""
        for i in range(len(a)):
            for b in range(10):
                if a[i]==str(b):
                    str_to_int_output+=a[i]
        return int(str_to_int_output)
    

    fn for "str to float" is a bit more comlicated, but i think i can do it if it is needed.

    0 讨论(0)
  • 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.

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