Convert String To List In Python

In this tutorial, I will show you different techniques for how to convert string to list in python. so without wasting any time let’s get started.

1. Convert String To List In Python By Using Split() Method

Split is the method of string data type that splits the string into a list using sep as the delimiter string. here is the syntax.

Syntax :

string.split(sep=None, maxsplit=-1)
  • sep : The delimiter to split the string into a list its default value is None which means split according to any whitespace and discard any empty strings from the result.
  • maxsplit : The maximum number of splits to do. default is -1 which means no split to do.

In this code example we will use this split() method to convert string to list.

#IDLE session to convert string to list in python
>>> string = "This Is A Test String"
>>> string.split() # by default split by whitespace character
['This', 'Is', 'A', 'Test', 'String']

>>> string = "This-Is-A-Test-String"
>>> string.split("-") # split by operator '-'
['This', 'Is', 'A', 'Test', 'String']

>>> string.split("-",maxsplit = 1) # if we only want 1 split
['This', 'Is-A-Test-String']

2. By Using list() Class

In this code example, we will directly apply the list() method to string hence converting it into a list.

>>> string = 'test boy'
>>> list(string)
['t', 'e', 's', 't', ' ', 'b', 'o', 'y']

3. By Using For-loop

In the below code, we will use the for loop to obtain the exact result as example 2.

The algorithm :

  • We first define an empty list.
  • Then we iterate through each character of the input list.
  • On each iteration, we add the character to the list.
>>> string = 'test boy'
>>> list1 = [] # define an empty list
>>> for i in string: # loop through each char
	     list1.append(i) # add to list
>>> list1
['t', 'e', 's', 't', ' ', 'b', 'o', 'y']

If you want to skip specific characters like whitespace from the final result list. you can do this way.

def converter(string,skips):
    """
    Function to convert string to list in python by skipping specific chars
    """
    result = [] # list to store result
    for i in string: # iterate through each char of list
        if i not in skips: # Check if char not is skips list
            result.append(i) # add to result list
    return result

# skip - and ' '
l1 = converter(string = 'This is-Test',skips = [' ','-'])
print(l1)

Save and run the above code you should see the following output.

Output :

['T', 'h', 'i', 's', 'i', 's', 'T', 'e', 's', 't']

Summary:

Here is summary of whole tutorial in one picture.

Summary of tutorial on how to convert string to list in python.

That wrap for the tutorial on how to convert string to list in python.

Also read about how to convert list to string in python.

Leave a Reply