Hi I'm trying to convert elements in an np array to string so that I can output them
with open("multiplication.txt", 'w') as output:
with open("data0.txt") as orig:
lines = orig.readlines()
for line in lines: # one line
b = np.fromstring(line, dtype=float, sep=' ') # convert to np array
for i in range(0, len(b)): #chage number values in b
if (b[i] > 3):
b[i] = str(5 * b[i])
else:
b[i] = str(3 * b[i])
output.write('\t'.join(string_b) + '\n')
When I ran the code I got an error:
Traceback (most recent call last):
File "C:\Users\Khant\Desktop\ex2.py", line 89, in <module>
output.write('\t'.join(b) + '\n')
TypeError: sequence item 0: expected str instance, float found
Then I found that though I have b[i] = str(5 * b[i]) but the elements in b actually are still float numbers rather than string. So I have to change the code like:
//...same code as above...//
for i in range(0, len(b)): #chage number values in b
if (b[i] > 3):
b[i] = 5 * b[i]
else:
b[i] = 3 * b[i]
string_b = [str(int(elem)) for elem in b] # convert to string
output.write('\t'.join(string_b) + '\n')
this time the code worked normally. So I just wonder why b[i] = str(5 * b[i]) cannot work like what I want?