Converting a string to an array in Python can be interpreted in different ways, depending on what you mean by “array”.
- If you mean a list (a kind of array commonly used in Python), you can simply convert each character or element of the string into an element of a list.
- If you mean an array in the context of numerical processing, such as a NumPy array, use the NumPy library.
Converting string to list
To convert a string into a list of words (splitting by spaces or another delimiter), use the split() method.
Visual Representation
Example 1: Convert String to a List of Words
string = "I love Python"
arr = string.split()
print(arr)
Output
['I', 'love', 'Python']
Example 2: Using a separator
string = "I,love,Python"
arr = string.split(',')
print(arr)
Output
['I', 'love', 'Python']
Example 3: Convert String to a List of Characters
To convert a string to a list of its characters, you can use list().
string = "Python"
arr = list(string)
print(arr)
Output
['P', 'y', 't', 'h', 'o', 'n']
Example 4: Using bytearray()
If you need a mutable array of bytes (for instance, for binary data processing), you can use bytearray().
string = "Python"
arr = bytearray(string, 'utf-8')
print(arr)
Output
bytearray(b'Python')
Convert String to NumPy Array
If you are working with numerical libraries like NumPy and want to convert a string to a NumPy array, you can do so as follows:
import numpy as np
my_string = "Python"
my_array = np.array(list(my_string))
print(my_array)
Output
['P' 'y' 't' 'h' 'o' 'n']
The output is the standard way NumPy displays arrays.
NumPy arrays do not use commas to separate elements, unlike Python lists. This is just a difference in the way NumPy and standard Python display arrays and lists, respectively.
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
You can use list comprehensions to do str -> char[] as well
str = ‘abc’
result = [c for c in str]
result
type(result)
// [‘a’,’b’,’c’]
// list
how to convert a list
1.2175443743582222
1.2175624154470546
1.216812476226702
1.2135922330097086
1.2135922330097086
1.2174474363703431
to
[1.2175443743582222,
1.2175624154470546,
1.216812476226702,
1.2135922330097086,
1.2135922330097086,
1.2174474363703431]
array.split(‘\n’)
This is a great tutorial on how to convert a string to an array in Python.