How can I convert a string to an int in Python?

前端 未结 8 1439
北恋
北恋 2020-11-27 21:35

The output I\'m getting for my little example app is the following:

Welcome to the Calculator!
Please choose what you\'d like to do:
0: Addition
1: Subtracti         


        
8条回答
  •  [愿得一人]
    2020-11-27 22:27

    Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)

    def convert(str):
        try:
            base = 10  # default
            if ':' in str:
                sstr = str.split(':')
                base, str = int(sstr[0]), sstr[1]
            val = int(str, base)
        except ValueError:
            val = None
    
        return val
    
    val = convert(raw_input("Enter value:"))
    # 10     : Decimal
    # 16:a   : Hex, 10
    # 2:1010 : Binary, 10
    

提交回复
热议问题