A string can be split into substrings using the split(param) method. This method is part of the string object. The parameter is optional, but you can split on a specific string or character.
Given a sentence, the string can be split into words. If you have a paragraph, you can split by phrase. If you have a word, you can split it into individual characters.
In most cases, the split() method will do. For characters, you can use the list method.
Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
If you have a string, you can subdivide it into several strings. The string needs to have at least one separating character, which may be a space.
By default the split method will use space as separator. Calling the method will return a list of all the substrings.
The demo below splits a string into characters.
s = "Its to easy"
words = s.split()
The len() method will give you the number of characters and number of words:
Output should be similar to the image below:
If you want to split a word into characters, use the list() method instead:
word = "Easy"
x = list(word)
A string can be reconstructed with the join method, which combines a sequence into a new string.
- Can a string be split on multiple characters?
- Can you split a string this string?: World,Earth,America,Canada
- Given an article, can you split it based on phrases?