Splitting and Joining Strings
As we've seen, there are lots of parallels between lists and strings, and in fact they go hand in hand!
Splitting strings
A common thing that we want to do with strings is to take a long string and break it into a list of shorter strings. For example, we may want to take a sentence and turn it into a list of words. This is done using the split method. Let's look at the following code to see how this works.
sentence:str = "Mary Lyon founded Mount Holyoke College."
# split the sentence into a list of words
words:list = sentence.split()
# print the first and last words
print( f"{words[0]}...{words[len(words)-1]}" )
which produces the following output:
Mary...College.
Joining strings
The join method works in the opposite operation. We can turn a list of strings into a single string. In this case, the string before the . is a “separator,” which is the value that is placed between the words. So, to turn a list of words into a sentence, we would use " " as the separator. Let's look at this code to see how it works.
# here's a list of words
words:list = ["Jorge", "loves", "Lower", "Lake"]
separator:str = " "
gooseFact:str = separator.join(words)
print(gooseFact)
# we can use a different separator than just a space
options:list = ["Yes", "No", "Maybe"]
separator:str = " / "
optionString:str = separator.join (options)
print(optionString)
which produces the following output:
Jorge loves Lower Lake
Yes / No / Maybe