Converting string to number? [duplicate] - python

This question already has an answer here:
Turning a list of strings into float
(1 answer)
Closed 9 years ago.
I should get this converted to numbers with float().
How can I do it?
Here is the code I have problems with. It´s simplified to the problem
poly = input().split()
poly.reverse()
return poly

Simply as you said in your question...you can use float:
>>> string = "1234.567"
>>> float(string)
1234.567

You can convert a string to a number in Python with the int(), float() and long() built-in functions.
E.g.
return int(poly)
See the Python docs for details:
int()
float()
long()

If poly is a list of strings you want to convert in floats, do:
floats = [float(s) for s in poly]

Related

Convert String with "." to int in python [duplicate]

This question already has answers here:
Convert a string to integer with decimal in Python
(8 answers)
Closed 4 months ago.
I want to convert a string with a point to a int
to us it in time
import time
x = "0.5"
time.sleep(int(x))
i tried it with this simple code but i get this error
ValueError: invalid literal for int() with base 10: '0.5'
is there an solutuion to convert the string to int
convert it to float first and then to int
x = "0.5"
print(int(float(x)))
you can convert this string to float and than use floor or ceil funtions for valid int
x = float(x)
x = math.floor(x) # or math.ceil() by your choice
x = int(x)

how to convert a string with floats numbers to another data type? [duplicate]

This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 10 months ago.
the string will be the price of some product, so it will basically come like this '1,433.10', the problem is that I need to compare it with the value that the user enters in an input that is only possible to enter integers because of the isdigit() method , used to check if the input is a number, and this causes the comparison to fail.
I already tried converting to int, to float and nothing worked, it only generated exceptions
def convert_values():
price = results['price'][2:] # here is where the string with the value is, which in this case is '1,643.10'
print(int(float(price))) # if I try to cast just to int: ValueError: invalid literal for int() with base 10: '1,643.10'
Before converting, replace the commas in the string with '' as:
price = results['price'][2:].replace(',', '')
print(int(float(price)))

Python - create separate lists but integers and strings not working [duplicate]

This question already has answers here:
Negative form of isinstance() in Python
(3 answers)
Closed 2 years ago.
Here's the info:
I have a list like this
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']
Looking to create three lists - integer, string and float
Integer list will have: 9,0,-5,1,-600,4
Float list will have: 0.7,5.9
String list will have: Europe,-9,English,0,-2,-3.7,Python
Wrote this program. Output was integers and integers marked as string. Not kind of what I want. Tweaked it to do the same with float. Did not work. Looking for a better way to get the desired output. Thanks!
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
try:
int_val = int(item)
print(int_val)
except ValueError:
pass
else:
newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
print(f'newlistint is : {newlistint}')
newlistonlyint.append(int_val)
print(f'newlistonlyint is :{newlistonlyint}')
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]
You can read about list comprehension here
int() tries to convert its argument to an int, raising a ValueError if this can’t be done. While it’s true that any integer argument to int() will not raise a ValueError, non-integer arguments like ‘9’ can be successfully converted to an integer (the integer 9 in this case), therefore not raising a ValueError.
Hence, trying to verify whether something is an integer by calling int() on it and catching ValueErrors just doesn’t work.
You should really be using the isinstance() function. Specifically, item is an int if and only if isinstance(item, int) returns True. Similarly, you can check for strings or floats by replacing int by str or float.

How to convert '1,0' to integer [duplicate]

This question already has answers here:
Convert decimal mark when reading numbers as input
(8 answers)
Closed 2 years ago.
As the title says, how would I go about converting '1,0' into 1,0 I've been getting ValueError: invalid literal for int() with base 10: '1,0'
First of all, 1,0 is generally not valid syntax for a float. You have to use 1.0. Second you can't convert 1.0 to an int, as this is a float. Use float("1.0") instead. If you need an int you can round the parsed float, e.g.
round(float("1.0"))
you can use:
int(float('1,0'.replace(',', '.')))

how to convert number < 1 from string to float python [duplicate]

This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 4 years ago.
my question is simple.
I got my string :
a = '0,0127'
I want to convert it to a number but when i compile
float(a)
i got the following message error :
ValueError: could not convert string to float: '0,0127'
Is there another way to convert it to a number ?
Using str.replace
Ex:
a = '0,0127'
print(float(a.replace(",", ".")))
Output:
0.0127
The reason this isn't working is because the decimal type only recognizes periods (.) for the decimal delimiter as this is what is common in, e.g., english. You could manually change the string or do
a = a.replace(",", ".")
float(a)
Which should work.

Categories

Resources