3

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]
2
  • do you plan to support negative numbers as well? as in ['-5', '-8.3'] Commented Dec 3, 2022 at 10:26
  • yes it should accept negative numbers aswell Commented Dec 3, 2022 at 10:49

5 Answers 5

8

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)
Sign up to request clarification or add additional context in comments.

2 Comments

voting up because It's a good answer but if there is a negative integer then it will convert to a negative float.
unfortunately, isdigit matches much more than just 0..9.
1

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

Comments

1

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

Comments

1

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]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.