Python: Convert a string to an integer

后端 未结 8 2077
余生分开走
余生分开走 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 01:45

    Under Python 3.0 (IDLE) this worked nicely

    strObj = "234\r\n"
    try:
        #a=int(strObj)
    except ValueError:
        #a=-1

    print(a) >>234


    If you're dealing with input you cannot trust, you never should anyway, then it's a good idea to use try, except, pass blocks to control exceptions when users provide incompatible data. It might server you better to think about try, except, pass structures as defensive measures for protecting data compatibility rather than simply hidding errors.

    try:
        a=int(strObj) #user sets strObj="abc"
    except ValueError:
        a=-1

    if a != -1:
        #user submitted compatible data
    else:
        #inform user of their error

    I hope this helps.

提交回复
热议问题