Strings are objects in Python. They have a method named split
that lets you
split the string.
For example, here is a string containing commas that we split:
>>> string = "red,blue,green"
>>> string.split(",")
['red', 'blue', 'green']
In general, the .split()
method takes a string as its argument, and returns
a list of strings.
You can split by a longer pattern:
>>> string = "this - also - works"
>>> string.split(" - ")
['this', 'also', 'works']
If you use split
without giving any arguments, then the string will be split
by any whitespace characters, such as spaces and tabs:
>>> string = "this is a\tstring"
>>> string.split()
['this', 'is', 'a', 'string']
The second argument to split is the maximum number of times to split:
>>> sentence = "hello world how are you"
>>> sentence.split(" ", 2)
['hello', 'world', 'how are you']
You can use the rsplit
method to split starting at the right instead of at
the left:
>>> sentence = "hello world how are you"
>>> sentence.rsplit(" ", 2)
['hello world how', 'are', 'you']
The join
method is the opposite of split. For example:
>>> sentence = "hello world how are you"
>>> words = sentence.split(" ")
>>> reconstructed = " ".join(words)
>>> print(reconstructed)
hello world how are you
The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!