Convert numpy, list or float to string in python

2024/10/9 0:45:37

I'm writing a python function to append data to text file, as shown in the following,

The problem is the variable, var, could be a 1D numpy array, a 1D list, or just a float number, I know how to convert numpy.array/list/float to string separately (meaning given the type), but is there a method to convert var to string without knowing its type?

def append_txt(filename, var):my_str = _____    # convert var to stringwith open(filename,'a') as f:f.write(my_str + '\n')

Edit 1: Thanks for the comments, sorry maybe my question was not clear enough. str(var) on numpy would give something like []. For example, var = np.ones((1,3)), str(var) will give [[1. 1. 1.]], and [] is unwanted,

Edit 2: Since I want to write clean numbers (meaning no [ or ]), it seems type checking is inevitable.

Answer

Type checking is not the only option to do what you want, but definitely one of the easiest:

import numpy as npdef to_str(var):if type(var) is list:return str(var)[1:-1] # listif type(var) is np.ndarray:try:return str(list(var[0]))[1:-1] # numpy 1D arrayexcept TypeError:return str(list(var))[1:-1] # numpy sequencereturn str(var) # everything else

EDIT: Another easy way, which does not use type checking (thanks to jtaylor for giving me that idea), is to convert everything into the same type (np.array) and then convert it to a string:

import numpy as npdef to_str(var):return str(list(np.reshape(np.asarray(var), (1, np.size(var)))[0]))[1:-1]

Example use (both methods give same results):

>>> to_str(1.) #float
'1.0'
>>> to_str([1., 1., 1.]) #list
'1.0, 1.0, 1.0'
>>> to_str(np.ones((1,3))) #np.array
'1.0, 1.0, 1.0'
https://en.xdnf.cn/q/70083.html

Related Q&A

Shared XMPP connection between Celery workers

My web app needs to be able to send XMPP messages (Facebook Chat), and I thought Celery might be a good solution for this. A task would consist of querying the database and sending the XMPP message to …

List of installed fonts OS X / C

Im trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?

How to detect changed and new items in an RSS feed?

Using feedparser or some other Python library to download and parse RSS feeds; how can I reliably detect new items and modified items?So far I have seen new items in feeds with publication dates earli…

python SharedMemory persistence between processes

Is there any way to make SharedMemory object created in Python persist between processes? If the following code is invoked in interactive python session: >>> from multiprocessing import share…

What is the difference between syntax error and runtime error?

For example:def tofloat(i): return flt(i)def addnums(numlist):total = 0for i in numlist:total += tofloat(i)return totalnums = [1 ,2 ,3] addnums(nums)The flt is supposed to be float, but Im confused whe…

Printing a line at the bottom of the console/terminal

Using Python, I would like to print a line that will appear on the last visible line on the console the script is being ran from. For example, something like this:Would this be able to be done?

Comparing first element of the consecutive lists of tuples in Python

I have a list of tuples, each containing two elements. The first element of few sublists is common. I want to compare the first element of these sublists and append the second element in one lists. Her…

Upload a file using boto

import boto conn = boto.connect_s3(, )mybucket = conn.get_bucket(data_report_321)I can download the file from a bucket using the following code.for b in mybucket:print b.nameb.get_contents_to_filename…

How to get n-gram collocations and association in python nltk?

In this documentation, there is example using nltk.collocations.BigramAssocMeasures(), BigramCollocationFinder,nltk.collocations.TrigramAssocMeasures(), and TrigramCollocationFinder.There is example me…

Using Python3 on macOS as default but pip still get using python 2.7

Im using macOS Big Sur 11.0.1. Im setting up a virtual env $python3 -m venv $my_workdir)/.virtualenvbut getting this error at building wheel package: building _openssl extensioncreating build/temp.maco…