0

Not a duplicate of Python - convert string to an array since answers there are relevant only for Python 2

How do I convert a string to a Python 3 array?

I know how to convert a string into a list:

>>> string = 'abcd'
>>> string
'abcd'

>>> list(string)
['a', 'b', 'c', 'd']

However, I need a Python array.

I need an answer specific for Python 3

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42

3 Answers3

2
import array as arr
output = arr.array('b', [ord(c) for c in 'abcdef'])

will output

array('b', [97, 98, 100, 101, 102])

Of course, you have to remember to convert back to characters with chr(), whenever you need to use them as letters/strings.

WGriffing
  • 604
  • 6
  • 12
1

My answer is limited to NumPy array. Try just this:

import numpy as np
array = np.array(list("acb"))

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

ipj
  • 3,488
  • 1
  • 14
  • 18
  • 3
    Unless they want a [python array](https://docs.python.org/3/library/array.html) – roganjosh Feb 27 '20 at 20:24
  • 1
    Why link to that w3schools page, of all things? They refer to a plain Python list as an array, and your answer is using NumPy ndarrays anyway. – AMC Feb 27 '20 at 20:46
-1

Given the following string

string = 'abcd'

There are two methods to convert it into an array.

Method 1:

Manually add to a list using a for loop:

array = []

for i in string:
    array.append(i)

Solution 2:

We can use list comprehension:

array = [i for i in string]
Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42