How can I split a string into a list in Python?
Alex K
alex k profile pic

In Python, you can split a string into a list using thesplit() method or thestr.split() function. Here's a detailed explanation of both approaches: Using the split() method: Thesplit() method is called on a string and splits it into a list of substrings based on a specified delimiter. By default, the delimiter is a whitespace character.

1
2
3
4
5
6

my_string = "Hello World"

split_list = my_string.split()

print(split_list)  # Output: ['Hello', 'World']

In this example,my_string.split() splits the stringmy_string into a list of substrings using the whitespace delimiter. The resulting list is assigned to the variablesplit_list. You can also specify a custom delimiter by passing it as an argument to thesplit() method. The method will split the string based on occurrences of the specified delimiter.

1
2
3
4
5
6

my_string = "apple,banana,orange"

split_list = my_string.split(',')

print(split_list)  # Output: ['apple', 'banana', 'orange']

In this case,my_string.split(',') splits the stringmy_string into a list of substrings using the comma (',') as the delimiter. Using the str.split() function: Alternatively, you can use thestr.split() function to split a string into a list. This function takes the string as an argument and returns a list of substrings based on the specified delimiter.

1
2
3
4
5
6

my_string = "Hello World"

split_list = str.split(my_string)

print(split_list)  # Output: ['Hello', 'World']

In this example,str.split(my_string) splits the stringmy_string into a list of substrings using the whitespace delimiter. Just like with thesplit() method, you can specify a custom delimiter by passing it as an argument to thestr.split() function.

1
2
3
4
5
6

my_string = "apple,banana,orange"

split_list = str.split(my_string, ',')

print(split_list)  # Output: ['apple', 'banana', 'orange']

In this case,str.split(my_string, ',') splits the stringmy_string into a list of substrings using the comma (',') as the delimiter. Both thesplit() method and thestr.split() function are effective ways to split a string into a list in Python. Choose the method that best fits your code style and requirements.