Reputation: 1359
In the following code snippet, I would like to avoid the usage of str()
in the function foo.
import numpy as np
def foo(a):
for runner in range(a.shape[0]):
row = a[runner, :]
toPrint = str(runner) + ' '+ str(row)
print(toPrint)
myArray = np.array(np.arange(9).reshape(3,-1)).astype('float')
foo(myArray)
output:
0 [0. 1. 2.]
1 [3. 4. 5.]
2 [6. 7. 8.]
Background: I use numba (https://numba.pydata.org/ ) where the usage of str()
in numba optimized functions is not possible.
How does the code of foo
have to look like, if no usage of str()
is allowed? Namely, no imports should happen (as numba most the times does not work with them).
Upvotes: 2
Views: 461
Reputation: 2061
If you would not like to use the str()
function in the function foo, why not append the results into a temporary list first before printing them out?
import numpy as np
list1 = []
def foo(a):
for runner in range(a.shape[0]):
row = a[runner, :]
toPrint = str(runner) + ' '+ str(row)
list1.append(toPrint)
myArray = np.array(np.arange(9).reshape(3,-1)).astype('float')
foo(myArray)
print(list1)
Upvotes: 1
Reputation: 22794
Consider string formatting:
toPrint = '{} {}'.format(runner, row)
print(toPrint)
Or simply (because there's a space separating the arguments by default):
print(runner, row)
# or [if you want to keep the toPrint variable]:
toPrint = (runner, row)
print(*toPrint)
Upvotes: 2