cobrexus
cobrexus

Reputation: 4808

How do I convert a string to an array?

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

Upvotes: 0

Views: 1227

Answers (3)

imcupcakegamer
imcupcakegamer

Reputation: 24

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]

Upvotes: -1

ipj
ipj

Reputation: 3598

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.

Upvotes: 1

WGriffing
WGriffing

Reputation: 624

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.

Upvotes: 2

Related Questions