You have two options for string formatting.
str.format()
, e.g. '{:16.8E}'.format(4.5)
- percent operator, e.g.
'%16.8E' % (4.5,)
The former is recommended for Python 3.x and any version higher than 2.6. The percent operator can be used for backwards compatibility with Python 2.5 or lower. For further discussion for which one you should use and where, read here. For some quick examples on how to format strings, check the documentation here.
I'll continue my answer using str.format()
, but using the other option would result in a very similar approach.
'{:16.8E}'
is what you need, so you want to repeat this 5 times for the whole line and respectively pass it 5 elements to print.
fmt = '{:16.8E}'
line_fmt = fmt * 5
print(line_fmt.format(*arr[0:5])) # `arr` is the name of your 1d array
The syntax *arr[0:5]
unpacks the values. This effectively passes 5 different arguments, arr[0], arr[1], arr[2], arr[3], arr[4]
, instead of one array with 5 elements.
You can use this repeatedly in a loop to print as many lines as you want. However, if you intend to print all elements, it's faster to print them in one go by preparing the string format to have newlines every fifth item.
import numpy as np
items_per_line = 5
np.random.seed(1024)
arr = np.random.random(size=12)
fmt = '{:16.8E}'
line_fmt = items_per_line * fmt
arr_fmt = [line_fmt] * (arr.shape[0] // items_per_line)
remainder = arr.shape[0] % items_per_line
if remainder:
arr_fmt.append(remainder * fmt)
arr_fmt = '\n'.join(arr_fmt)
print(arr_fmt.format(*arr))
Result
6.47691231E-01 9.96913580E-01 5.18803264E-01 6.58112731E-01 5.99063472E-01
7.53067334E-01 1.36247128E-01 4.11711641E-03 1.49508880E-01 6.98439001E-01
5.93352562E-01 8.99915349E-01