2

I just learned that numpy.fromstring() is a handy function:

a = ('1 2 3')
# convert to list of numbers
b = np.fromstring(a, sep=' ')

Now I modified the b and want to convert it back to a list of strings. Is there a built-in function in numpy to do that?

Sorry my original question might be not accurate. What I want to do is to convert b into the same format as a.

user3768495
  • 4,077
  • 7
  • 32
  • 58

4 Answers4

3
In [490]: a='1 2 3'

If you want b elements to be integers, as opposed to float, specify the dtype.

In [491]: b=np.fromstring(a, sep=' ',dtype=int)
In [492]: b
Out[492]: array([1, 2, 3])
In [493]: b += 2            # typical array math
In [494]: b
Out[494]: array([3, 4, 5])

Normal array display string, via print or str. Note that the array str omits the comma; that's just a visual clue distinguishing it from a list.

In [495]: print(b)
[3 4 5]
In [496]: str(b)
Out[496]: '[3 4 5]'

We can strip off the [] to get a display like a

In [497]: str(b)[1:-1]
Out[497]: '3 4 5'

But ' '.join is a good list formatting trick:

In [500]: [str(i) for i in b]
Out[500]: ['3', '4', '5']
In [501]: ' '.join([str(i) for i in b])
Out[501]: '3 4 5'

We could just as easily split a into a list of strings, modify those, and rejoin

In [506]: a1=a.split()
In [508]: a1
Out[508]: ['1', '2', '3']
In [509]: a1[1]='34'
In [510]: a1
Out[510]: ['1', '34', '3']
In [511]: ' '.join(a1)
Out[511]: '1 34 3'
hpaulj
  • 221,503
  • 14
  • 230
  • 353
1

According to these answers ans.1 & ans.2:

You can solve this by python itself or using numpy.

pure python solution:

map(str, b)
# ['1.0' '2.0' '3.0']

numpy solution:

list(np.char.mod('%d', b))
# ['1' '2' '3']
Community
  • 1
  • 1
amin
  • 1,413
  • 14
  • 24
1

List comprehension solution:

' '.join(str(x) for x in b)
# '1.0 2.0 3.0'

or:

' '.join("%d" % x for x in b)
# '1 2 3'
DYZ
  • 55,249
  • 10
  • 64
  • 93
0

Just figured (probably) the easiest way:

str(b)

:0)

user3768495
  • 4,077
  • 7
  • 32
  • 58