Home > Enterprise >  How to convert string to number in python?
How to convert string to number in python?

Time:12-04

I have list of numbers as str

li = ['1', '4', '8.6']

if I use int to convert the result is [1, 4, 8]. If I use float to convert the result is [1.0, 4.0, 8.6]

I want to convert them to [1, 4, 8.6]

I've tried this:

li = [1, 4, 8.6]
intli = list(map(lambda x: int(x),li))
floatli = list(map(lambda x: float(x),li))
print(intli)
print(floatli)

>> [1, 4, 8]
>> [1.0, 4.0, 8.6]

CodePudding user response:

Convert the items to a integer if isdigit() returns True, else to a float. This can be done by a list generator:

li = ['1', '4', '8.6']
lst = [int(x) if x.isdigit() else float(x) for x in li]
print(lst)

To check if it actually worked, you can check for the types using another list generator:

types = [type(i) for i in lst]
print(types)

CodePudding user response:

To convert a string to a number in Python, you can use the int() or float() function to convert the string to an integer or a floating-point number, respectively. For example, if you have the following string:

string = "123"

You can use the int() function to convert the string to an integer, like this:

number = int(string)

This will assign the value 123 to the number variable.

Alternatively, if the string contains a decimal point, you can use the float() function to convert the string to a floating

CodePudding user response:

One way is to use ast.literal_eval

>>> from ast import literal_eval
>>> spam = ['1', '4', '8.6']
>>> [literal_eval(item) for item in spam]
[1, 4, 8.6]

Word of caution - there are values which return True with str.isdigit() but not convertible to int or float and in case of literal_eval will raise SyntaxError.

>>> '1²'.isdigit()
True

CodePudding user response:

You can use ast.literal_eval to convert an string to a literal:

from ast import literal_eval

li = ['1', '4', '8.6']
numbers = list(map(literal_eval, li))

As @Muhammad Akhlaq Mahar noted in his comment, str.isidigit does not return True for negative integers:

>>> '-3'.isdigit()
False

CodePudding user response:

You're going to need a small utility function:

def to_float_or_int(s):
    n = float(s)
    return int(n) if n.is_integer() else n

Then,

result = [to_float_or_int(s) for s in li]

CodePudding user response:

In Python, you can convert a string to a number using the int() or float() functions. For example, if you have a string like "123", you can convert it to the integer number 123 using the int() function like this:

string = "123"
number = int(string)

Or, if you have a string like "3.1415", you can convert it to the float number 3.1415 using the float() function like this:

string = "3.1415"
number = float(string)

These functions will raise a ValueError if the string cannot be converted to a number, so you should make sure to check for that and handle it appropriately in your code. For example:

string = "hello"
try:
    number = int(string)
except ValueError:
    print("The string cannot be converted to a number.")

I hope that helps! Let me know if you have any other questions.

CodePudding user response:

You can try map each element using loads from json:

from json import loads
li = ['1', '4', '8.6']
li = [*map(loads,li)]
print(li)

# [1, 4, 8.6]

Or using eval():

print(li:=[*map(eval,['1','4','8.6','-1','-2.3'])])

# [1, 4, 8.6, -1, -2.3]

Notes:

Using json.loads() or ast.literal_eval is safer than eval() when the string to be evaluated comes from an unknown source

  • Related