How to convert a string to a list | Python

Method 1:
string to list character-wise

syntax:
list[:0] = string

Don’t know how to convert a number to a list in Python? Read: How to convert a number to a list in Python

Example 1:

# Python program to understand how to convert a string to a list in Python
# www.codewindow.in
s = "codewindow is a website"
x = []
x[:0] = s
print(x)

Output:

['c', 'o', 'd', 'e', 'w', 'i', 'n', 'd', 'o', 'w', ' ', 'i', 's', ' ', 'a', ' ', 'w', 'e', 'b', 's', 'i', 't', 'e']

Explanation:
Here all the characters of the string are converted to elements in the list.

Method 2:
using split()

Syntax:
string.split(seperator)

Example 1:

# Python program to understand how to convert a string to a list in Python
# www.codewindow.in
s = "codewindow is a website"
x = s.split()
print(x)

Output:

['codewindow', 'is', 'a', 'website']

Explanation:
Here all the words in the string are converted into a list as separate strings.

Example 2:

# Python program to understand how to convert a string to a list in Python
# www.codewindow.in
s = "codewindow-is a-website"
x = s.split("-")
print(x)

Output:

['codewindow', 'is a', 'website']

Explanation:
Here the elements are separated by “-”. Therefore wherever it finds the “-” it separated the string there and returned a list of the separated items.


You Missed

Also Checkout