python

Split string to list python

Python has a built-in function called split() that can be used to split a string into a list of substrings. The split() function takes a string and a delimiter as arguments and returns a list of substrings. The delimiter can be any character, such as a space, a comma, or a tab.

my_str = "This is a string"
print(my_str.split()) # split uisng space
# -> ['This', 'is', 'a', 'string']

comma_str = "Apple,Banana,Orange"
print(comma_str.split(", ")) # split using comma
# -> ['Apple', 'Banana', 'Orange']

Output

["This", "is", "a", "string"]
["Apple", "Banana", "Orange"]

In the above code examples, the first example splits a string into a list of substrings based on whitespace. The second example does the same but uses a comma and space as the delimiter.

Split string using split() function

Python provides a very straightforward method to split strings using the split() function. This function takes a single argument, which is a delimiter and splits the string based on that delimiter. The delimiter can be any character, such as a space, comma, or tab.

The split() function returns a list of strings, which you can then access using indexes. For example, if you have a string that contains a list of fruits, you can use the split() function to get a list of those fruits.

>> fruits = 'apple,banana,cherry,orange'

>> fruits.split(',')

['apple', 'banana', 'cherry', 'orange']

You can also access individual items in the list using indexes. For example, if you want to get the first fruit in the list, you would use an index of 0.

>> fruits[0]

'apple'

If you want to get the last fruit from the list, you would use an index of -1.

>> fruits[-1]

'orange'

You can also use the split() function to split a string on multiple delimiters.

Code example

# define a string
names_str = "John-Martin-Stevan-Seol"

# split the string using - delimiter
names_list = names_str.split("-")

print(names_list)

Output

['John', 'Martin', 'Stevan', 'Seol']

This code example defines a string, names_str, containing four names separated by dashes. It then uses the string's split() method to create a list, names_list, containing those same names. Finally, it prints the list.

Was this helpful?