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

时间:2010-10-20 14:43:18

标签: 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"

8 个答案:

答案 0 :(得分:16)

由于您正在编写一个可能也接受浮点数(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转换不起作用,你将得到一个浮动返回。

编辑:如果您不完全了解how python 2.x handles integer division,您的division功能也可能会导致一些悲伤的面孔。

简而言之,如果您希望10/2等于2.5 2,则需要from __future__ import division或投一个def division(a, b): return float(a) / float(b) 或者两个浮动的参数,如下所示:

{{1}}

答案 1 :(得分:11)

>>> a = "123"
>>> int(a)
123

这是一些免费赠品代码:

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

容易!

    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

答案 4 :(得分:0)

def添加(a,b):     返回a + b

def减法(a,b):     返回a - b

def乘法(a,b):     返回a * b

def division(a,b):     返回a / b

keepProgramRunning = True

打印“欢迎使用计算器!”

while keepProgramRunning:
    打印“请选择您要做的事情:”

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)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

答案 5 :(得分:0)

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

import sys

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

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

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

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

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

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

    if int(choice) == 5:
        a = input("Enter the base number\n")
        b = input("Enter the exponential\n")
        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时调用每个函数。我希望这会有所帮助。

在你的情况下,它可以像这样改变:

 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))

答案 6 :(得分:0)

不要直接在html中使用str()方法,而是与 y = x | string()

一起使用
<div class="row">
    {% for x in range(photo_upload_count) %}
        {% with y=x|string() %}

    <div col-md-4 >
        <div class="col-md-12">
            <div class="card card-primary "  style="border:1px solid #000">
                <div class="card-body">
                    {% if data['profile_photo']!= None: %}
                        <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                    {% else: %}
                        <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                    {% endif %}
                </div>
                <div class="card-footer text-center">
                    <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}
</div>

答案 7 :(得分:-1)

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:"