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']
["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.
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'
['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.
If you want to get the last fruit from the list, you would use an index of -1.
You can also use the split() function to split a string on multiple delimiters.
# define a string names_str = "John-Martin-Stevan-Seol" # split the string using - delimiter names_list = names_str.split("-") print(names_list)
['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.