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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
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()作为字符串而不是数字。如何将它们用作数字?

这是我的整个剧本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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"
"


因为您编写的计算器可能也接受浮动(1.5, 0.03),所以更健壮的方法是使用这个简单的助手函数:

1
2
3
4
5
6
7
8
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返回。

编辑:如果您不完全了解python 2.x如何处理整数除法,那么您的division函数也可能导致一些悲伤的面孔。

简而言之,如果你想让10/2等于2.5而不是2,你就需要做from __future__ import division,或者让其中一个或两个论点浮动,就像这样:

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


1
2
3
>>> a ="123"
>>> int(a)
123

以下是一些免费代码:

1
2
3
4
def getTwoNumbers():
    numberA = raw_input("Enter your first number:")
    numberB = raw_input("Enter your second number:")
    return int(numberA), int(numberB)


从主函数调用子函数时,可以将变量转换为int,然后调用。请参考以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import sys

print("Welcome to Calculator
"
)
print("Please find the options:
"
+"1. Addition
"
+"2. Subtraction
"
+
"3. Multiplication
"
+"4. Division
"
+"5. Exponential
"
+"6. Quit
"
)

def calculator():
    choice = input("Enter choice
"
)

    if int(choice) == 1:
        a = input("Enter first number
"
)
        b = input("Enter second number
"
)
        add(int(a), int(b))

    if int(choice) == 2:
        a = input("Enter first number
"
)
        b = input("Enter second number
"
)
        diff(int(a), int(b))

    if int(choice) == 3:
        a = input("Enter first number
"
)
        b = input("Enter second number
"
)
        mult(int(a), int(b))

    if int(choice) == 4:
        a = input("Enter first number
"
)
        b = input("Enter second number
"
)
        div(float(a), float(b))

    if int(choice) == 5:
        a = input("Enter the base number
"
)
        b = input("Enter the exponential
"
)
        exp(int(a), int(b))

    if int(choice) == 6:
        print("Bye")
        sys.exit(0)



def add(a, b):
    c = a+b
    print("Sum of {} and {} is {}".format(a, b, c))

def diff(a,b):
    c = a-b
    print("Difference between {} and {} is {}".format(a, b, c))

def mult(a, b):
    c = a*b
    print("The Product of {} and {} is {}".format(a, b, c))

def div(a, b):
    c = a/b
    print("The Quotient of {} and {} is {}".format(a, b, c))

def exp(a, b):
    c = a**b
    print("The result of {} to the power of {} is {}".format(a, b, c))

calculator()

我在这里做的是在将输入的参数转换为int时调用每个函数,希望这有帮助。

在您的情况下,可以这样更改:

1
2
3
4
5
 if choice =="0":
        numberA = raw_input("Enter your first number:")
        numberB = raw_input("Enter your second number:")
        print"Your result is:"
        print addition(int(numberA), int(numberB))

添加DEF(A、B):返回A+B

定义减法(a,b):返回-B

DEF倍增(A、B):返回A*B

DEF部门(A、B):返回A/B

keepProgramrunning=真

打印"欢迎使用计算器!"

保持编程运行时:打印"请选择要执行的操作:"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 = input("Enter your first number:")
    numberB = input("Enter your second number:")
    print"Your result is:" + str(addition(numberA, numberB)) +"
"

elif choice =="1":
    numberA = input("Enter your first number:")
    numberB = input("Enter your second number:")
    print"Your result is:" + str(subtraction(numberA, numberB)) +"
"

elif choice =="2":
    numberA = input("Enter your first number:")
    numberB = input("Enter your second number:")
    print"Your result is:" + str(multiplication(numberA, numberB)) +"
"

elif choice =="3":
    numberA = input("Enter your first number:")
    numberB = input("Enter your second number:")
    print"Your result is:" + str(division(numberA, numberB)) +"
"

elif choice =="4":
    print"Bye!"
    keepProgramRunning = False
else:
    print"Please choose a valid option."
    print"
"


容易的!

1
2
3
4
5
6
    if option == str(1):
        numberA = int(raw_input("enter first number."))
        numberB= int(raw_input("enter second number."))
        print""
        print addition(numberA, numberB)
     etc etc etc

也许下面,那么您的计算器就可以使用任意的基数(例如十六进制、二进制、基数7!)等):(未测试)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:"