Given a collection of string values, the task is to create a string array in Python. Depending on the requirement, string arrays can be created using lists, NumPy arrays, or other Python data structures. For Example:
Input: fruits = ["Apple", "Mango", "Orange"]
Output: ['Apple', 'Mango', 'Orange']
Now, let's explore different methods to create a string array in Python.
Using List
A list is a common way to store multiple strings in Python. Each string becomes an individual element of the list and can be accessed, modified, or removed using its index.
arr = ["Apple", "Mango", "Orange"]
print(arr)
print(arr[1])
Output
['Apple', 'Mango', 'Orange'] Mango
Explanation: list stores each string as a separate element. The expression arr[1] accesses the second element of the list.
Using NumPy Array
NumPy provides the array() function to create arrays containing string values. All strings are stored together in a NumPy array, making them easy to access and process.
import numpy as np
arr = np.array(["Apple", "Mango", "Orange"])
print(arr)
print(arr[2])
Output
['Apple' 'Mango' 'Orange'] Orange
Explanation: np.array() function creates a NumPy array from the given strings. Individual elements can be accessed using their index.
Using List Comprehension
If the string values are generated dynamically, list comprehension can be used to create the string array while constructing the list.
words = ["python", "java", "c++"]
arr = [w.title() for w in words]
print(arr)
Output
['Python', 'Java', 'C++']
Explanation: List comprehension iterates through each string, converts it to title case, and stores the resulting strings in a new list.
Using Array Module
The array module does not support storing multiple strings directly. Instead, it stores individual Unicode characters using the 'u' type code.
from array import array
arr = array('u', "Python")
print(arr)
print(arr[2])
Output
array('u', 'Python')
t
Explanation: array('u', ...) object stores each character of the string as a separate Unicode element. It does not create an array of multiple strings, but rather an array of individual characters.