如何去除numpy数组字符串表示中的方括号?
It looks like your error comes from trying to join elements that are actually sub-arrays (not raw strings), probably because your NumPy array is multi-dimensional (e.g., 2D instead of 1D). Here are two straightforward ways to get the exact formatted string you want:
Option 1: Use NumPy's array2string (Quickest Method)
This leverages NumPy's built-in formatting to handle the quotes and spacing, then we just strip the surrounding brackets:
For a 1D array:
import numpy as np thearray = np.array(['w_49c9417', 'w_b6ae946', 'w_1596a47', 'w_b68d04']) result = np.array2string(thearray, separator=' ')[1:-1] print(result)
If your array is multi-dimensional (which is likely causing your join error), flatten it first:
result = np.array2string(thearray.flatten(), separator=' ')[1:-1]
This will output exactly what you need: 'w_49c9417' 'w_b6ae946' 'w_1596a47' 'w_b68d04'
Option 2: Explicit Join with List Comprehension
If you prefer a more Pythonic, explicit approach, you can iterate over the array elements, wrap each in single quotes, then join with spaces:
For 1D arrays:
result = ' '.join(f"'{item}'" for item in thearray)
For multi-dimensional arrays:
result = ' '.join(f"'{item}'" for item in thearray.flatten())
Why Your Original join Failed
The error TypeError: sequence item 0: expected str instance, numpy.ndarray found happens because each element in your array is actually a small sub-array (e.g., from a 2D array like [[...], [...]]), not a direct string. Flattening the array converts it to a 1D sequence of strings, which join can work with correctly.
Content's question comes from Stack Exchange, question author Ryan

