In Python, you can split a string into a list of substrings using the split() method. The split() method takes an optional argument that specifies the delimiter character to use for splitting the string. If no delimiter is specified, whitespace characters (i.e., spaces, tabs, and newlines) are used as the delimiter.
Here's an example of splitting a string using the split() method:
text = "This is a sentence that we want to split into words."# Split the string into words using whitespace as the delimiterwords = text.split()# Print the list of wordsprint(words) |
Output:
['This', 'is', 'a', 'sentence', 'that', 'we', 'want', 'to', 'split', 'into', 'words.'] |
In this example, we split the string text into a list of words using whitespace as the delimiter. The split() method returns a list of substrings, which we assign to the variable words. We then print the list of words to the console.
You can also specify a custom delimiter character to split the string. Here's an example:
text = "John,Doe,1980-01-01,1234 Main St.,Anytown,USA"# Split the string into a list using a comma as the delimiterparts = text.split(',')# Print the list of partsprint(parts) |
Output:
['John', 'Doe', '1980-01-01', '1234 Main St.', 'Anytown', 'USA'] |
In this example, we split the string text into a list of parts using a comma as the delimiter. The resulting list contains the individual parts of a comma-separated value (CSV) record.