Python string to list – Complete tutorial

In this Python tutorial, you will learn about Python String to list. Let us see how to convert Python string to list and also we will cover the below examples:

  • Python string to list of characters
  • Python string to list conversion
  • Python string to list with separator
  • Python string to list of words
  • Python string to list split
  • Python string to list of ints
  • Python string to list with spaces
  • Python string to list newline
  • Python string to list of dictionaries
  • Python string to list of strings
  • Python string to list by delimiter
  • Python string to list of floats
  • Python string to list array
  • Python string to list without split
  • Python add string to list elements
  • Python string list extract substring
  • Python string split to list regex
  • Python string list remove duplicates
  • Python string list index
  • Python string to list of tuples
  • Python string to list of json
  • Python string to list remove spaces
  • Python string list to dataframe
  • Python string list max length
  • Python string list to byte array
  • Python string vs list

Python string to list

  • In this program, we are going to learn how to convert a string to a list in Python.
  • To convert a string to a list in Python we can easily apply the split() method. This method will help the user to break up a string at a given separator and it always returns the split string in a list.
  • In Python string if the delimiter is not given in the function as a parameter or if by default its value is none then a different splitting algorithm is applied.

Syntax:

Here is the Syntax of the split() function

String.split(separator,maxsplit)
  • It consists of a few parameters
    • Separator: It is an optional parameter and it is used to split the string if not provided then whitespace will be considered as a delimiter.
    • Maxsplit: It specifies how many splits are required in the function.

Example:

Let’s take an example and check how to convert a string to a list.

new_str = "java is a best programming language"

new_lis = list(new_str.split(" ")) 
print("convert str to list:",new_lis) 

In the above code first, we initialize a string ‘new_str’ and then use the split() method and pass whitespace as a delimiter which splits the words of the string, and stores them into the list.

Here is the Screenshot of the following given code

Python string to list
Python string to list

Read Remove character from string Python (35 Examples)

Convert a string to a list in Python

By using the Python list() function we can perform this particular task and this method takes iterable objects and converts them into the list.

Here is the code of string to list in Python

new_val = "john is a good boy"

new_out = list(new_val.strip(" "))
print(new_out)

In this example, we use the concept of strip() function and it will remove spaces from the string at the first and the end of the string.

Here is the execution of the following given code

Python string to list
Python string to list

Read How to create a string in Python

Python string to list of characters

  • Let us see In Python, how to convert a string into a list of characters by using the inbuilt list() method.
  • In Python the list() constructor generates a list directly from iterable objects and it always returns a list of all the characters which is available in the string and in this example we have to pass a string object to the list() method.

Syntax:

Here is the Syntax of a list() method

list(iterable)
  • It consists of only one parameter
    • Iterable: This parameter can be used as a sequence or we can say any other iterable objects.

Source Code:

give_str = 'Micheal'

new_val2 = list(give_str)
print(new_val2) 

In the above code, we have already taken the input string ‘Micheal’ and now we use the list() constructor and it will give us a list having the individual characters ‘M’, ‘i’ as elements.

Here is the implementation of the following given code

Python string to list of characters
Python string to list of characters

Read Python list comprehension using if-else

Check how to convert a string into a list of characters

By using the Python list comprehension method we can convert a string into a list of characters. In Python, the list comprehension method is used to build a new list. List comprehension is an easy way to define and declare lists based on existing lists.

Here is the Source code:


str_new = 'Australia'
 
new_char = [i for i in str_new]
print(new_char) 

In the above example, a list is assigned to a variable ‘str_new’, and the list stores the items of the iterable objects. After that, we call print() statement to display the output.

Here is the execution of the following given code

Python string to list of characters
Python string to list of characters

Read Python remove substring from a String + Examples

Python string to list conversion

  • Let us see how to converse a string into a list in Python.
  • In this example, we use the concept of a split() function and if you want to break a string to list then you did not provide any separator or delimiter to the split method. If the delimiter is not given in the function parameter then by default it takes none value.

Syntax:

Here is the Syntax of the split() function

string.split(delimiter, maxsplit)

Example:

pro_lang = "Python developer"

new_char = pro_lang.split()
print("Conversion string to list:",new_char)

Here is the Output of the following given code

Python string to list conversion
Python string to list conversion

Read Python 3 string replace() method

Python string to list with separator

  • In Python to convert a string into a list with a separator, we can use the str. split() method.
  • In this example, we can use the comma-separated string ‘,’ and convert them into a list of characters. In python, the split() function is basically used to break a string into a list on the basis of the separator.
  • Here we have mentioned the separator parameter in the split() method.

Here is the Source Code:

stu_name = "oliva,Elijah,Potter"

new_lis = stu_name.split(",")
print(new_lis)

Output:

Python string to list with separator
Python string to list with separator

Read Python compare strings

Python string to list of words

  • Let us see how to convert a string into a list of words in Python, the easiest way to solve this problem is to use the split() method and this method will break a string into a list where each word is a list item.
  • In this example by default, the delimiter for this function is whitespace and we have to split the first index element.

Source Code:

def convert(Country_name):
    return (Country_name[0].split())
 
Country_name = ["Australia Germany"]
print(convert(Country_name))

In the above code first, we define a function ‘convert’ and then pass list ‘country_name’ as an argument. Now create a list and call print() statement to display the result.

Here is the execution of the following given code

Python string to list of words
Python string to list of words

Read Python 3 string methods with examples

Python string to list split

  • Here we can see how to convert a string to a list by using the split() method in Python.
  • In Python, the split() method always returns a list of the words in the string and also divides a string into a list. By default, the separator is a whitespace character like space, ‘ ‘,\n, etc.

Syntax:

Here is the Syntax of the split() function

string.split(separator,maxsplit)

Source Code:

new_str = 'John,micheal,George'

print(new_str.split('-'))

Here is the Output of the following given code

Python string to list split
Python string to list split

Read Python find substring in string

Python string to list of ints

  • Let us see how to convert a string list to an integer list in Python.
  • By using the list comprehension method we can perform this particular task, this method is used to build a new list where each list element is to iterate.

Example:

val_lis = ['16', '87', '27', '19', '145']

new_char = [int(x) for x in val_lis]
print ("updated list is : ",new_char)

In the above example we have a list ‘val_lis’ and then apply the built-in function int and get a list of integers by using the list comprehension method.

Here is the implementation of the following given code

Python string to list of ints
Python string to list of ints

How to convert a string list to an integer

By using the map and split() function we can solve this problem, In Python, the map() function is well efficient and easy to convert a list of strings into integer and this method always returns an iterator, convert the string into an integer list.

Source Code:

new_char = "15 27 89"

val_list = new_char.split()
new_item = map(int, val_list)
d = list(new_item)
print(d)

Here is the Screenshot of the following given code

Python string to list of ints
Python string to list of ints

Read Could not convert string to float Python

Python string to list with spaces

  • Here we can see how to convert a string to a list with whitespace in Python.
  • To perform this task we can use the function join(). In Python, the join() function is a string method that returns str by combining all the elements of iterable objects and separated by ‘ ‘.

Source Code:

def convert(new_name):
      
    return ' '.join(new_name)
new_name = ['Adam','Hayden','Chris']
print(convert(new_name))

Here is the Output of the following given code

Python string to list with spaces
Python string to list with spaces

Read Slicing string in Python

How to convert a string to a list with spaces

By using the ‘*’ operator we can convert a string to a list with white spaces in Python. In this example first, we declare a list ‘new_val_lis’ and store them integer values.

Source Code:

new_val_lis = [16,82,93,46]
print(*new_val_lis)

new_val = ['lily','rose','jasmine']
print(*new_val)

Here is the Screenshot of the following given code

Python string to list with spaces
Python string to list with spaces

Read Convert string to float in Python

Python string to list newline

  • Here we can see how to split a string along with the newline delimiter in Python. To do this task first we will declare a list of all lines in the string separated at line ends.
  • By using “\n”,”\r” special characters we can separate the characters in a given string and these line boundaries are defined as splits in the string.

Example:

new_variable = "z y u \n i t a \r t z x"

new_sep_char = new_variable.splitlines()
print(new_sep_char)

Here is the execution of the following given code

Python string to list newline
Python string to list newline

Read Append to a string Python

Cconvert strings into a list using newline – Another approach

By using the splitline() method we can solve this problem and this function is used to split the lines at line boundaries in Python.

Source Code:

new_string1 = 'Oliva\nis\nagood\nprogrammer'

new_str2= new_string1.splitlines()
print(new_str2)

Here is the Screenshot of the following given code

Python string to list newline
Python string to list newline

Read Add string to list Python + Examples

Python string to list of dictionries

  • Let us see how to convert a string to a list of dictionaries in Python.
  • To perform this particular task we can use the method eval(). This method checks the data type and returns the result in the form of a list. In Python, the eval() is a built-in function and it evaluates the string and converts them into the list.

Source Code:

country_str = "[{'australia' : 15, 'England' : 19}, {'Germany' : 27, 'Europe' : 37}]"

new_output = list(eval(country_str))
print(new_output)

In the above example first, we initialize a string and then use the eval() method to convert a list of dictionaries.

Here is the implementation of the following given code

Python string to list of dictionaries
Python string to list of dictionaries

Read Python program to reverse a string with examples

Python string to list of strings

  • In Python to convert string to list of strings we can use the split() function and this method will help the user to break a string into a list where each word is a list item.

Example:

pro_sting =" Mongodb sql java"

print("original str: ",pro_sting) 
print("Convert string to list of str :",pro_sting.split()) 

In the above code first, we consider a string, ‘pro_sting’, and then apply the split() function. It is used to break a string into a list on the given separator. In this example, we have not mentioned the separator argument is a split() function.

Here is the Output of the following given code

Python string to list of strings
Python string to list of strings

Read Python string formatting with examples

Python string to list by delimiter

  • Here we can see how to convert a string to a list by using a delimiter in Python.
  • By default, the delimiter takes whitespace and separates the words but in this example, we have mentioned ‘,’ as a delimiter in split() function.

Source Code:

alpha_str = 'o,q,e,x,c'

new_list = alpha_str.split(",")
print (new_list)

In the above code first, we consider a string ‘alpha_str’ and assign them characters in single-quoted ‘ ‘. Now we can use the split() function and pass ‘,’ delimiter as an argument.

Here is the Output of the following given code

Python string to list by delimiter
Python string to list by a delimiter

Read How to concatenate strings in python

Python string to list of floats

  • By using the map and split() function we can perform this task, In Python, the map() function is well efficient and easy to convert a list of strings into floats and this method always returns an iterator, to convert the string into a float list.

Source Code:

flo_str = "31.9 23.4 118.3"

new_val_lis = flo_str.split()
new_item = map(float, new_val_lis)
z = list(new_item)
print("Convert string to float list:",z)

In this example, we have created a string ‘flo_str’ and assign them float values. Now by using the map() function we have passed float data type as an argument and store them into a ‘new_item’ variable.

Output:

Python string to list of floats
Python string to list of floats

Read How to Convert Python string to byte array with Examples

Another example by using list comprehension and eval() method

  • You can also convert a string to a list of float numbers by using Python in-built function eval() and list comprehension.
  • In Python the list comprehension method declares new lists from other iterables like strings and the eval() method parses expression parameters and checks the arithmetic expression as a string.

Example:

i = ["4.2", "85.1", "92.5"]

new_float_value = [eval(z) for z in i]
print(new_float_value)

Here is the Screenshot of the following given code

Python string to list of floats
Python string to list of floats

By using for loop and split() method we can a string to a list of floats in Python

Source Code:

new_floa_str = "76.4 35.8 167.9"

emp_lis = []
for i in new_floa_str.split():
  emp_lis.append(float(i))

print(emp_lis)

In this example, we have created a list of items by space in a string, we can use the split() and along with use for loop to iterate each item in a given list. After that use float datatype to convert each item to a float number.

Screenshot:

Python string to list of floats
Python string to list of floats

Read How to convert a String to DateTime in Python

Python string to list array

  • Let us see how to convert a string to an array in Python.
  • To do this we can use the split() method and this method will help the user to split the elements as individually into list items. In the split() method you can specify the separator but in this example, by default, the separator is the white space.

Syntax:

Here is the Syntax of the split() method

String.split(separator, maxsplit)

Example:

Let’s take an example and check how to convert a string into an array

new_alpha = "Python is a best programming language"

new_array = new_alpha.split()
print(new_array)

In the above example, we have split the string by using a white space delimiter.

Output:

Python string to list array
Python string to list array

Read Python generate random number and string

Python string to list without split

  • Here we can see how to convert a string to a list without using split() method in Python.
  • The simplest way to break a string in Python, we can use the list slicing method. In the list slicing method first and last indexes are separated by a colon[:]. If we did not set the value for the first index then by default it takes 0 and the last index is set to the end element of the list.

Syntax:

list[start:stop:step]

Source Code:

new_character = "Micheal"

empty_list = []

empty_list[:] = new_character
print('Convert string to list:',empty_list)

Here is the execution of the following given code

Python string to list without split
Python string to list without split

This is how to split a string into a list without using the split() function in Python.

Read Python write String to a file

Python add string to list elements

  • In Python how to add a string into a list of elements, we can apply the append() function in Python, and this method will add new items to the end of a list.
  • In this example, we have specified a single item to add one string to a list and it does not return a new list but it will update the original list by inserting the element to the last of the list.

Source Code:

new_str_lis = ['a','z','x','c']

add_str = 'uveq'
new_str_lis.append(add_str)
print("list after appending string is:",new_str_lis)

In the above example first, we initialize a list and create a string ‘add_str’ which we have to add to a list. Appending string to a list we can use the method append() and this particular function add a string element to the last of a list without changing the list of characters.

Here is the execution of the following given code

Python add string to list elements
Python add a string to list elements

Read How to handle indexerror: string index out of range in Python

Python string list extract substring

  • Here we can see how to extract substring from the given string in Python.
  • In Python, we can easily solve this task by using the slicing method. In this program, we have to access the sub-string of a string. A substring is a sequence of characters inside a string.
  • To extract a substring from a string in Python we can apply the string slicing method.

Syntax:

Here is the Syntax of the slice() method

slice(start,stop,step)

Note: This method consists of three parameters start, stop, step, and the slice object is inserted within the string variable.

Example:

ext_str = "oplrtwe"

new_slic =slice(2)
new_slic2 = slice(3)
print(ext_str[new_slic])
print(ext_str[new_slic2])

In the above example, we pass single integer value ‘2’ as an argument in the slice() constructor and the index value starts from 0.

Here is the execution of the following given code

Python string list extract substring
Python string list extract substring

Read How to convert list to string in Python

Python string split to list regex

  • Here we can see how to split a string based on the regex pattern in Python.
  • To split the string by regular expression we can use the re. split() method. In Python, the re.split() method returns a list of strings by comparing all circumstances of the given pattern in the string.
  • Regular expression uses the backslash character(‘\’) but in this example we use the underscore delimiter(‘_’).

Syntax:

Here is the Syntax of re.split() function

re.split(pattern, string, maxsplit=0, flags=0)
  • This method consists of four arguments.
    • Pattern: The regular expression pattern uses as a delimiter and it is also used for splitting the string.
    • String: The variables or words that you want to split from the list of strings.
    • Maxsplit: It is an optional parameter and by default, the maxsplit argument is 0.
    • flags: It is an optional flag and by default, no flags are required in this method.

Source Code:

import re

nw_string1 = "13__oliva,,eljiah,_john_,Micheal"
reg_exp_str = re.split('[_,][_,]',nw_string1)
print(reg_exp_str)

In the above code first, we have created a string ‘nw_string1’ and in this string, each word is separated by underscore and comma. Now this delimiter(‘_’) is used to break the string into substrings.

Output:

Python string split to list regex
Python string split to list regex

Read How to convert an integer to string in python

Python string list remove duplicates

  • Let us see how to remove duplicates from a list string in Python.
  • You can remove duplicates from the list by using the set() method. In Python, the set() method cannot contain any duplicate values and this method will help the user to convert into a new list in which duplicate characters are removed.

Let’s take an example and check how the set() method can be used to remove duplicates from the list.

Source Code:

new_str = ['a','g','j','i','u','p','u','i','z']

rem_new_dup = list(set(new_str))
print(rem_new_dup)

In the above code first, we initialize a list called ‘new_str’ which contains alphabet characters. Now we declare a variable ‘rem_new_dup’ which stores the set() function and assign ‘new_str’ variable as an argument. This process deletes all duplicates from a given list.

Here is the execution of the following given code

Python string list remove duplicates
Python string list remove duplicates

How to remove duplicate string from list

  • You can also remove duplicates from the list by using dict.keys() method in Python. This method will always return a unique value. In Python, the dictionaries cannot contain duplicate values so that’s why we use dict.keys() method in this example.
  • The dict.keys() method will help the user to remove duplicate words or characters from the list.

Syntax:

Here is the Syntax of dict.keys() method

dict.fromkeys(keys,value)

Note: This method consists of two parameters key and value.

Example:

string =['john','micheal','australia','micheal','germany','george','john']

remove_dupli = list(dict.fromkeys(string))
print(remove_dupli)

In the above code first, we have created a string called ‘string’ which contains different countries’ names in the form of a string. Now use the dict.fromkeys() method to initialize a dictionary from the ‘string’ variable and then use the list() constructor to convert dict into a list.

Screenshot:

Python string list remove duplicates
Python string list remove duplicates

Read How to split a string using regex in python

Python string list index

  • Here we can see how to get index value from the list which contains string elements in Python.
  • By using the list index() method we can perform this task and it is an inbuilt function in Python that finds the elements from the start of the list.

Syntax:

Here is the Syntax of a list index() method

list.index(element, start, end)
  • It consists of a few parameters
    • element: This parameter specifies which element you want to get the index value.
    • Start: It’s an optional parameter and by default, its value is 0.
    • End: If you want to find the last index element then you can use this parameter.

Example:

student_name = ['George', 'James', 'Potter', 'Oliva']

new_ind = student_name.index('James')
print(new_ind)

In the above example, we have created a list ‘student_name’ which contains strings. Now I want to get the index value of ‘james’ to do this we apply the list.index() method and call the print statement to display the index value.

Here is the execution of the following given code

Python string list index
Python string list index

Read Python dictionary of tuples

Python string to list of tuples

  • Let us see how to convert a string to a list of tuples in Python.
  • The combination of iter()+split()+next() can be used to perform this particular task. In this example, we use the iterator object that contains a countable element and the next() method is used to fetch the next element from the collection.

Source Code:

new_val_str = "Java is a core programming language"

new_out = iter(new_val_str.split())

lis_of_tup = [(new_element, next(new_out)) for new_element in new_out]
print(lis_of_tup)

Here is the Output of the following given code

Python string to list of tuples
Python string to list of tuples

Read Python sort list of tuples

Python string to list of json

  • Here we can see how to convert a string to a list by importing JSON library in Python.
  • In this programm, we use the JSON.loads() method. In Python, the JSON.loads() method takes a JSON string as a parameter and it will return the list-objects.

Source Code:

import json
  
first_list1 = "[45,7,8,2,3,4]"
new_output = json.loads(first_list1)
print ("Convert string to list:", new_output)
Python string to list of json
Python string to list of JSON

Read Python concatenate tuples with examples

Python string to list remove spaces

  • To remove whitespace in the list we can apply the replace() and append() method with for loop.
  • In this example, we have created a list “new_lis” which contains elements in the form of string. Now create an empty list and use for loop method to iterate items from the original list and then use replace() method for removing white space in a list.

Example:

new_lis = ['John', '   ', 'James ', 'Micheal', '  ', 'George']

new_output = []
for val in new_lis:
    m = val.replace(' ', '')
    new_output.append(m)

print(new_output)

Output:

Python string to list remove spaces
Python string to list remove spaces

Read Python square a number

Python string list to dataframe

  • Let us see how to convert a string into a list by using a dataframe in Python. To do this task first we import a pandas library in it.
  • In Python, the dataframe is a data structure in the form of rows and columns.

Here is the Screenshot and code of the CSV file

Note: This code is an input string you have to use in your CSV file

student_id|batch
23|"[batch3,batch8]"
24|"[batch7,batch18,batch78]"
19|"[batch65,batch34]"
Python string to list csv file
Python string to list CSV file

Here is the implementation of the string list to the dataframe.

Source code:

import pandas as pd

df = pd.read_csv('test1.csv', sep='|')
print(df)

In the above first we import a pandas library and then create a variable ‘df’ in which we have used the ‘read_csv’ function for importing a CSV file to dataframe format. In this method, we have assigned a ‘test.csv’ file as an argument.

Output:

Python string list to dataframe
Python string list to dataframe

Read Python print without newline

Python string list max length

  • Let us see how to find a maximum length in a string list in Python.
  • To perform this task we can use the inbuilt max() function with the “len” constructor as a key parameter and this method return the maximum string.

Source Code:

original_lis1 = ['Micheal', 'john', 'george', 'potter', 'james']

new_output = max(original_lis1, key = len)
print(new_output)

Here is the execution of the following given code

Python string list max length
Python string list max length

Python string list to byte array

  • To convert a string to a byte array we can simply pass the string as the first input and then pass the encoding ‘utf-8’ as a second parameter.
  • In this example first, we have created a string ‘count_str’ and then create a variable ‘new_array’ in which we have stores bytes() method and assign string as an argument.

Source Code:

count_str = "Germany"

new_array = bytes(count_str, 'utf-8')

for new_byte in new_array:
    print("Convert string to byte:",new_byte)

Here is the implementation of the following given code

Python string list to byte array
Python string list to byte array

Read Python naming conventions

Python string vs list

  • In Python, the list can store any data type while a string can only consist of characters.
  • In Python list can be easily declared by square brackets[] and a string is a sequence of characters within the single or double quotes.
  • In a list, data can be separated by a comma(,) and the data can be integer, float, and string. While the string is an immutable datatype.

Example:

Let’s take an example and check the main difference between string and list in Python

new_str = 'James' #create string

print("created string:",new_str)
my_new_list = [35,87,66] #create list

print("Created list:",my_new_list)

Here is the execution of the following given code

Python string vs list
Python string vs list

You may like the following Python tutorials:

In this Python tutorial, you will learn about Python String to list. Let us see how to convert Python string to list and also we will cover the below examples:

  • Python string to list of characters
  • Python string to list conversion
  • Python string to list with separator
  • Python string to list of words
  • Python string to list split
  • Python string to list of ints
  • Python string to list with spaces
  • Python string to list newline
  • Python string to list of dictionaries
  • Python string to list of strings
  • Python string to list by delimiter
  • Python string to list of floats
  • Python string to list array
  • Python string to list without split
  • Python add string to list elements
  • Python string list extract substring
  • Python string split to list regex
  • Python string list remove duplicates
  • Python string list index
  • Python string to list of tuples
  • Python string to list of json
  • Python string to list remove spaces
  • Python string list to dataframe
  • Python string list max length
  • Python string list to byte array
  • Python string vs list