Python | Splitting a string into a list of characters



Let`s discuss some ways to accomplish this task.

Method # 1: Using List Slicing
List Slicing can be used for this specific purpose, in which we assign each the list index item is the next occurrence of the line character, using the slice operation.

# Python3 demo code
# splitting the string into a list of characters.
# using a slice of the list

 
# initializing string

test_string = "GeeksforGeeks"

 
# print original string

print ( "The original string is:" + str (test_string))

 
# using list slicing
# to split the string into a list of characters

res = []

res [: 0 ] = test_string

 
# print result

print ( "The resultant list of characters:" +   str (res))

Exit:

The original string is: Python.Engineering
The resultant list of characters: [` G `,` e `,` e `,` k `,` s`, `f`, `o`, `r`, `G`, `e`, ​​`e`, ​​`k`, `s` ]

Method # 2: Using list()
The shortest and most readable way to do parsing — put the case string into the list, and the list splitting is automatically handled internally. This is the recommended method for this specific task.

Exit:

The original string is: Python.Engineering
The resultant list of characters: [`G`, `e`, `e`, ​​`k`, `s`, `f`, `o`, `r`, `G`, `e`, ​​`e`, ​​`k`, `s`]

Method # 3: Using map () + lambda
This is another way to accomplish this particular task. Although not recommended, it can be used in certain situations. But the downside is that code readability is sacrificed.

# Python3 demo code
# splitting lines to a list of characters.
# using a list ()

 
# initializing string

test_string = "GeeksforGeeks"

 
# print original string

print ( "The original string is: " + str (test_string))

 
# using the list ()
# to split the string into a list of characters

res = list (test_string)

 
# print result

print ( " The resultant list of characters: " +   str (res))

# Python3 demo code
# splitting the string into a list of characters.
# using map () + lambda

  
# initialization string

test_string = " Python.Engineering "

  
# print the original line

print ( " The original string is: " + str (test_string ))

 < br /> # using the () + lambda map
# to split the string into a list of characters

res = list ( map ( lambda i: i, test_string))

 
# print result

print ( "The resultant list of characters:" +   str (res))

Exit:

The original string is: Python.Engineering
The resultant list of characters: [`G`, `e`, ​​`e`, ​​`k`, `s`,` f `,` o `,` r `,` G `,` e `,` e `,` k `,` s`]