<tutorialjinni.com/>

Python convert string to array of chars

Posted Under: Programming, Python, Tutorials on Nov 6, 2024
To convert a string into an array (or list) of characters in Python, you can use the list() function. Here’s how
text = "Hello String"
char_array = list(text)
print(char_array)
['H', 'e', 'l', 'l', 'o']
Alternatively, you can use a list comprehension:
# Define the string
text = "Hello, World!"

# Use a list comprehension to create a list of characters
char_array = [char for char in text]

# Print the result
print(char_array)
If you run this code, char_array will contain each character from text as a separate element, including spaces, punctuation, or special characters. Here’s what the output will look like:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']


imgae