pythonarraysnumpychars

Turn NumPy Array of characters into a string


I have a numpy array of characters and when I write it to file it writes as:

['K' 'R' 'K' 'P' 'T' 'T' 'K' 'T' 'K' 'R' 'G' 'L']

I want it to write with just the letters and without the brackets or quotations i.e. as:

KRKPTTKTKRGL 

I have looked at numpy documentation and from what I have gathered the solution is a chararray however it looks like this is not as functional as a normal array.

Any help would be great. Thanks!


Solution

  • You can use tostring() method of numpy as:

    >>> st = np.array(['K' 'R' 'K' 'P' 'T' 'T' 'K' 'T' 'K' 'R' 'G' 'L'])
    >>> st.tostring()
    'KRKPTTKTKRGL'
    

    Since you have a numpy array, this method will be faster than join().

    For Python3x tostring() can be used as:

    >>> st = np.array(['K','R','K','P','T','T','K','T','K','R','G','L'])
    >>> st.astype('|S1').tostring().decode('utf-8')
    'KRKPTTKTKRGL'