|
Splitting a StringTo create a list from a string, use the split function. Here is a simple example:
In this call to split, the parameter "," specifies the substring that is to be used to break the string into a list. The substring can be a single character or any number of characters, and is not included as part of the resulting list. In this example, split assumes that its string is a collection of words separated by commas. It creates a new list element (or word) every time it sees a comma. Since there are four commas in the string, there are five elements, or words, in the resulting list. You can specify a maximum number of string breaks to perform. To do this, provide the maximum number as the second parameter to split. For example:
This call to split only performs one break, creating a list of two elements: the first word, and everything else. To reassemble a string that has been broken into a list using split, use join. For example, here is code that uses split and join to replace one word in a comma-separated list of words:
When you call join, you must specify two things: the string to be used to join the list into a string, and the list to be joined. Note that the join string must be specified first. In this example, because the join string is ",", a comma-separated string is built, with Rehabilitation used in place of Treatment.
|