Python: Convert a string to an integer

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

    int('243\r\n'.strip())

    But that won't help you, if something else than a number is passed. Always put try, except and catch ValueError.

    Anyway, this also works: int('243\n\r '), so maybe you don't even need strip.

    EDIT:

    Why don't you just write your own function, that will catch the exception and return a sane default and put into some utils module?

提交回复
热议问题