Python split string into list

Hello coders, In this tutorial you learn how to split string into list in python. There are different technique or methods for splitting python string into list, we will see each one in this tutorial.

Python split string into list
  • List Typecasting

python programming give us list() function for type casting any python data types into list. You can also used this list() function for splitting python string into list.

def split(words):
   return list(word)

word="programiz"
print(split(word))

Output:

['p','r','o','g','r','a','m','i','z']
  • Using split() function

You can also used split() function for splitting string into list. This split() function return list of words from string. You can also define separator in split function, the default separator in split() function is black space.

n='7 1 2'
l=s.split()
print(l)

Output:

[7,1,2]
  • List comprehension method

The another technique for converting string to list is by using list comprehension method. By using below syntax you can easily split string into list.

def split("words"):
   return [char for char in word]
word='programiz'
print(split(word))

Output:

['p','r','o','g','r','a','m','i','z']
  • Using Shlex module

You can also used shlex module for splitting python string to list. Refer the below syntax to split string into list in python.

import shlex

w='1 2 3'
l=shlex.split(w)
print(l)

Output:

['1','2','3']
Was this article helpful?
YesNo

1 thought on “Python split string into list”

  1. Pingback: buy social signals

Leave a Comment