Convert list in String format back to list of float numbers

2024/11/15 17:25:38
str = [  3.82133931e-01   4.27354313e-02   1.94678816e-03   0.00000000e+000.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+000.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+000.00000000e+00   3.61185198e-06   1.26606241e-01   1.18472360e-01]

The above string has been retrieved from a database text field and I'm trying to convert it back into a list of floats however no matter what I try I can't seem to get rid of the square brackets.

floatList = []for k, v in enumerate(str.split('   ')):if re.search(r'\d', v):item = re.sub(r'\D\S', '', v).rstrip()item = re.sub(r'\[.*?\]/g', '', item)floatList.append(float(item))

I have tried:

item.replace('[', '')
item.replace(']', '')

and with the Ascii codes.

Always the error ValueError: could not convert string to float: '[ 536444501'

Answer

It seems like you should be able to just strip off the [ and ]:

str = str.replace('[', '').replace(']', '')

And then split the string calling float on each member of the split string:

floats = [float(x) for x in str.split()]

Notice that because python strings are immutable, things like:

str.replace('[', '')

Doesn't change str in place. Instead, it returns a new string with the requested characters removed. Since it returns a new string, we need to give that string a name (I just chose to give it the name str1 again to avoid using too many names...)

1Note that str is also not a good name for a variable since it shadows the builtin str type. I would highly recommend picking a different name :-)

https://en.xdnf.cn/q/119286.html

Related Q&A

Hawaiian Pronunciation [duplicate]

This question already has an answer here:Hawaiian pronouncer(1 answer)Closed 1 year ago.Hitting a snag with an assignment and thought Id ask for help. The goal is to be able to pronounce Hawaiian words…

mutiline python script in html (pyscript)

Ive tried to use pyscript in html but i can only get it to work in one line of code can somebody help me get it to work for the following code? def vpn(website):from selenium import webdriverfrom sele…

How to write an output of a command to stdout and a file in Python3?

I have a Windows command which I want to write to stdout and to a file. For now, I only have 0 string writen in my file:#!/usr/bin/env python3 #! -*- coding:utf-8 -*-import subprocesswith open(auto_cha…

Mongodb adding a new field in an existing document, with specific position

I am facing this issue where I need to insert a new field in an existing document at a specific position. Sample document: { "name": "user", "age" : "21", "…

how to check every 3 x 3 box in sudoku?

I am trying to build a sudoku solver without much googling around. Right now, I am working on a function to test whether the board is valid, which I will use later in a loop. This is what the function …

multiple model accuracy json result format using python

I am building a multiple model and i am getting results with 7 models accuracy, i need those results with a proper json format.My multiple model building code will be like thisseed = 7"prepare mod…

Calculate Time Difference based on Conditionals

I have a dataframe that looks something like this (actual dataframe is millions of rows):ID Category Site Task Completed Access Completed1 A X 1/2/22 12:00:00AM 1/1/22 12:00:00 AM1 A Y 1/3/22 12:00:00A…

Cannot open jpg images with PIL or open()

I am testing to save ImageField in Django, but for some reason all the *.jpg files Ive tried dont work while the one png I had works. Using django shell in WSL VCode terminal. python 3.7 django 3.0 pil…

how to delete tensorflow model before retraining

I cant retrain my image classifier with new images, I get the following error:AssertionError: Export directory already exists. Please specify a different export directory: /tmp/saved_models/1/How do I …

Use beautifulsoup to scrape a table within a webpage?

I am scraping a county website that posts emergency calls and their locations. I have found success webscraping basic elements, but am having trouble scraping the rows of the table. (Here is an example…