Python Forum
Converting str to int or float
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting str to int or float
#3
As you already found out, split() parses the values in strings. So 3 + 4 is really string concatenation and gives a result of 34.

For extra credit you could:
a. Check to make sure you have exactly 3 items in the expression len(expression).
b. Assuming you are working with integers only, you could check that num1 and num2 are numbers (e.g. num1.isdigit()).
c. Checking for 'float' is probably beyond the scope of this exercise. The following working code is probably for future reference in combining float and int:
def get_int_or_float(v):
    # NOTE: '1.0' will be identified as type 'int'
    try:
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        if number_as_float == number_as_int:
            return number_as_int
        else :
            return number_as_float
    except:
        return v

num1 = '1'
num1 = get_int_or_float(num1)
print(num1, type(num1))

num1 = '1a'
num1 = get_int_or_float(num1)
print(num1, type(num1))


num1 = '1.1'
num1 = get_int_or_float(num1)
print(num1, type(num1))

num2 = 3.3

if isinstance(num1, str) or isinstance(num2, str):
    # this would be the error branch
    print("string")
else:
    # this would be the calculation branch - exactly as you have it
    print("int or float or combination of both")

Output:
1 <class 'int'> 1a <class 'str'> 1.1 <class 'float'> int or float or combination of both
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply


Messages In This Thread
Converting str to int or float - by juliabrushett - Jun-16-2018, 06:53 PM
RE: Converting str to int or float - by ichabod801 - Jun-16-2018, 07:06 PM
RE: Converting str to int or float - by ljmetzger - Jun-17-2018, 09:57 AM
RE: Converting str to int or float - by volcano63 - Jun-17-2018, 03:05 PM
RE: Converting str to int or float - by DeaD_EyE - Jun-17-2018, 06:28 PM
RE: Converting str to int or float - by volcano63 - Jun-17-2018, 08:08 PM
RE: Converting str to int or float - by DeaD_EyE - Jun-18-2018, 10:08 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020