8

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 string
    with 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.

2

4 Answers 4

6

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

import numpy as np

def to_str(var):
    if type(var) is list:
        return str(var)[1:-1] # list
    if type(var) is np.ndarray:
        try:
            return str(list(var[0]))[1:-1] # numpy 1D array
        except TypeError:
            return str(list(var))[1:-1] # numpy sequence
    return 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 np

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

2 Comments

np.savetxt can also be used to save numpy arrays in a readable way, array.tolist() creates a nested list for you
@jtaylor That's not a bad idea. However, for that to work, you would have to convert all types into a np.array. And when that is done, you might as well just convert it to string yourself. I edited my answer to include that method.
4

str is able to convert any type into string. It can be numpy.array / list / float

# using numpy array
new_array = numpy.array([1,2,3])
str(new_array)
>> '[1 2 3]'

# using list
new_list = [1, 2, 3]
str(new_list)
>> '[1, 2, 3]'

# using float
new_float = 1.1
str(new_float)
>> '1.1'

5 Comments

When it's some string with weird encoding, str() can raise some weird error.
Can you list the string and the error that was raised?
I was thinking about unicode string, str(u"\u03A9") raises an UnicodeEncodeError
The unicodeEncodeError doesn't occur in Python3. If you are using Python 2, you can use str(var).encode('utf-8')
Good to know this is possible.
1

If you don't know what is the type of var you can check type using

from collections import Iterable
if isinstance(var,Iteratable):
    mystring=''.join(map(str,var))
else:
    mystring=str(var)

2 Comments

this would work, btw, there is a typo: if isinstance(var,Iterable):
str(numpy array) will not print the full array if its large, you have to change the print options, convert to list or use savetxt to get all data in text form
1

Maybe what you're looking for is repr()

It's the opposite of the eval function.

Here's what eval does:

eval('[1,3]')
# [1, 3]

Here's what repr does:

repr('example')
# "'example'"
repr(0.1)
# '0.1'
repr([1,2])
# '[1,2]'

1 Comment

However, repr(np.ones((1,3))) will give 'array([[ 1., 1., 1.]])'. Good idea, though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.