How do I Split string into list of characters in python

Given a string, write a Python program to split the characters of the given string into a list using Python.

Examples:

Input : programmingshark
Output : ['p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k']

Input : Word
Output : ['W', 'o', 'r', 'd'] 

Method 1: Split a string into a Python list using unpack(*) method

The act of unpacking involves taking things out, specifically iterables like dictionaries, lists, and tuples.

Python3

string = "programmingshark"
print([*string]) 

Output: 

['p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k'] 

Method 2: Split a string into a Python list using a loop

Here, we are splitting the letters using the native way using the loop and then we are appending it to a new list.

Python3 

string = 'programmingshark'
lst = []

for letter in string:
    lst.append(letter)

print(lst) 

Output:

['p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k'] 

Method 3: Split a string into a Python list using List Comprehension

This approach uses list comprehension to convert each character into a list. Using the following syntax you can split the characters of a string into a list.

Python3 

string = "programmingsharkforprogrammingshark "
letter = [x for x in string]
print(letter) 

Output: 

['p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k' 'f', 'o', 'r', 'p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k'] 

Method 4: Split a string into a Python list using a list() typecasting

Python provides direct typecasting of strings into a list using Python list().

Python3  

def split(word):
    return list(word)
    
# Driver code
word = 'programmingshark'
print(split(word)) 

def split(word):
    return list(word)
 

Output: 

['p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k'] 

Method 5: Split a string into a Python list using extend()

Extend iterates over its input, expanding the list, and adding each member.

Python3 

string = 'programmingshark@for'
lst = []
lst.extend(string)
print(lst) 

Output: 

['p', 'r', 'o', 'g', 'r' 'a', 'm', 'm', 'i', 'n' 'g' 's', 'h', 'a', 'r' 'k' '@', 'f', 'o', 'r'] 

 

 

Submit Your Programming Assignment Details