python - 如何在 Python 中将字符串转换为 int?

标签 python string int

我的小示例应用程序的输出如下:

Welcome to the Calculator!
Please choose what you'd like to do:
0: Addition
1: Subtraction
2: Multiplication
3: Division
4: Quit Application
0
Enter your first number: 1
Enter your second number: 1
Your result is:
11

这是因为 addition() 方法将 input() 作为字符串而不是数字。如何将它们用作数字?

这是我的整个脚本:

def addition(a, b):
    return a + b

def subtraction(a, b):
    return a - b

def multiplication(a, b):
    return a * b

def division(a, b):
    return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:    
    print "Please choose what you'd like to do:"

    print "0: Addition"
    print "1: Subtraction"
    print "2: Multiplication"
    print "3: Division"
    print "4: Quit Application"



    #Capture the menu choice.
    choice = raw_input()    

    if choice == "0":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print addition(numberA, numberB)
    elif choice == "1":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print subtraction(numberA, numberB)
    elif choice == "2":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print multiplication(numberA, numberB)
    elif choice == "3":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print division(numberA, numberB)
    elif choice == "4":
        print "Bye!"
        keepProgramRunning = False
    else:
        print "Please choose a valid option."
        print "\n"

最佳答案

由于您正在编写一个可能也接受 float 的计算器 (1.5, 0.03),因此更可靠的方法是使用这个简单的辅助函数:

def convertStr(s):
    """Convert string to either int or float."""
    try:
        ret = int(s)
    except ValueError:
        #Try float.
        ret = float(s)
    return ret

这样,如果 int 转换不起作用,您将返回一个 float。

编辑:如果您不完全了解 how python 2.x handles integer division,您的 division 函数也可能会导致一些悲伤的表情.

简而言之,如果您希望 10/2 等于 2.5 2,您将需要执行 from __future__ import division 或将一个或两个参数转换为 float,如下所示:

def division(a, b):
    return float(a) / float(b)

关于python - 如何在 Python 中将字符串转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3979077/

相关文章:

Python SimpleXMLRPCServer : Socket Error , 连接被拒绝

python - 在Python中循环和计算json响应

python - 如何匹配同一数据集的 lomb-scargle 和 FFT 图?

string - bash:在多个其他字符串中查找字符串

python - 如何检查是否有相同的数字,然后打印最大的数字

python - 是否有与 Perl 的 x 运算符(复制字符串)等效的 Python?

python - 为什么 `str.format()` 会忽略其他/未使用的参数?

c++ - 如何从字符串中获取浮点值?

c++ - 将 int 转换为 char*

C在while循环中读取输入