Splitting String to List of Characters Python (original) (raw)
Last Updated : 30 Jan, 2025
We are given a string, and our task is to split it into a list where each element is an individual character. **For example, if the input string is “hello”, the output should be [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]. Let’s discuss various ways to do this in Python.
Using list()
The simplest way to split a string into individual characters is by using the list() function.
Python `
s = "python"
Splitting into characters
res = list(s)
print(res)
`
Output
['p', 'y', 't', 'h', 'o', 'n']
**Explanation:
- list(s) converts the string into a list of characters.
- Each character in s becomes an individual element in result.
Let’s explore some more ways and see how we can split a string into a list of characters.
Table of Content
Using List Comprehension
List comprehension provides a compact way to iterate over the string and extract characters.
Python `
s = "python"
Splitting into characters
res = [char for char in s]
print(res)
`
Output
['p', 'y', 't', 'h', 'o', 'n']
**Explanation:
- The for loop extracts each character from s into a list.
- This approach is useful when additional conditions or transformations are needed.
Using map()
map() function applies str on each character of the string and returns an iterable, which we convert to a list.
Python `
Initializing string
s = "python"
Splitting into characters
res = list(map(str, s))
print(res)
`
Output
['p', 'y', 't', 'h', 'o', 'n']
**Explanation:
- map(str, s) processes each character individually.
- The result is converted to a list for easier manipulation.
Using re.findall()
Regular expressions can be used to match individual characters in the string.
Python `
import re
Initializing string
s = "python"
Splitting into characters
res = re.findall(r'.', s)
print(res)
`
Output
['p', 'y', 't', 'h', 'o', 'n']
**Explanation:
- re.findall(r’.’, s) matches each character separately.
- This approach is useful when additional pattern-based filtering is needed.