Python: Convert a string to an integer

后端 未结 8 2099
余生分开走
余生分开走 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条回答
  •  萌比男神i
    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.

提交回复
热议问题