Peter Raeves
Peter Raeves

Reputation: 516

How should I make a big string of floats?

I'm creating an arff file with a lot of numeric data. Now since my feature vector is quite large, I ended up with code like this

with(file,'w') as myfile:
    s = number + ","
    s += number + ","
    s += number + ","
    s += number + ","
    ...
    myfile.write(s)

Since I'm quite new to Python I obviously forgot about the fact that Python doesn't seem to allow floats to be concatenated to strings like that and giving me the following error.

unsupported operand type(s) for +: 'numpy.float64' and 'str'

So how would a more experienced python programmer deal with this problem or do I really have to cast all those numbers to strings like this

with(file,'w') as myfile:
    s = str(number) + ","
    s += str(number) + ","
    s += str(number) + ","
    s += str(number) + ","
    ...
    myfile.write(s)

Upvotes: 2

Views: 60

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121654

Don't write CSV rows by hand. Use the csv module:

with(file, 'wb') as myfile:
    writer = csv.writer(myfile)
    writer.writerow([number1, number2, number3])

Each element in the list is converted to a string for you.

When using numpy arrays, you can use numpy.savetext() to achieve much the same results.

Even without the csv module, you can just a sequence of values into one string with str.join(), with a judicious helping of map() to make sure all values are strings:

s = ','.join(map(str, [number1, number2, number3]))

A quick demo of the latter (using Python 2):

>>> number = 42.4245
>>> string = 'The quick brown fox'
>>> empty = None
>>> map(str, [number, string, empty])
['42.4245', 'The quick brown fox', 'None']
>>> ','.join(map(str, [number, string, empty]))
'42.4245,The quick brown fox,None'

Upvotes: 7

Related Questions