Having trouble converting a list of strings into numbers

Si Random :

So I got a list here:

list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]

And I want its output to be this so that all the numbers in my list are now "floats" but still string form:

["yo dog", "2.0", "it's ya boi", "jake", "69.420"]

This is what I tried:

list1 = [float(x) for x in list1 if is_number(x)]

list1 = [str(x) for x in list1]

Basically it leaves me with:

["2.0", "69.420"] and removes everything else that's not a number. This is obvious because I'm making my old list equal to only the strings that have numbers in them.

(is_number() btw is my function to check if a string contains a number)

So obviously I could make a for loop and add stuff together again, but I was wondering if there was a better way to do this.

I HAVE NEGATIVE NUMBERS!!!

kederrac :

you could use a regular expression:

import re 

list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]

[str(float(e)) if re.match(r'^-?\d+(?:\.\d+)?$', e) else e  for e in list1 ]

output:

['yo dog', '2.0', "it's ya boi", 'jake', '69.42']

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=278910&siteId=1