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

18
  • 8
    What do you mean by Array? Is it NumPy array? Commented Feb 27, 2020 at 20:17
  • 5
    what do you mean by array? Python does not have a built-in type of array. in most cases, list type is a perfect substitute for an array Commented Feb 27, 2020 at 20:17
  • 1
    @kyriakosSt That isn't true Commented Feb 27, 2020 at 20:23
  • 2
    @AryanBeezadhur What does an array mean to you? And what differentiates the type list? Commented Feb 27, 2020 at 20:34
  • 2
    How is this specific to Python 3? Commented Feb 27, 2020 at 20:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Unless they want a python array
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.
-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]

1 Comment

This is for converting a string to a list, not an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.