split, join and strip
Text that a program reads often holds several values on one line: words in a sentence, numbers separated by commas. split cuts a string into a list of pieces. Without an argument, it cuts at spaces:
sentence = "the quick brown fox"
words = sentence.split()
print(words)
print(len(words), "words, the last is", words[-1])
print("a,b,,c".split(","))
['the', 'quick', 'brown', 'fox']
4 words, the last is fox
['a', 'b', '', 'c']With an argument, split cuts at that text instead. Two commas in a row give an empty piece between them.
The pieces are always strings. Numbers on a line must go through int, one at a time:
line = input("Two numbers: ")
parts = line.split()
a = int(parts[0])
b = int(parts[1])
print("Sum:", a + b)
15 27Two numbers: 15 27
Sum: 42Joining
join goes the other way: it joins a list of strings into one string. The string you call it on goes between the pieces. It looks backwards at first, but read it as "join these, with this between them":
words = ["red", "green", "blue"]
print(", ".join(words))
print("".join(words))
print(" -> ".join(sorted(words)))
red, green, blue
redgreenblue
blue -> green -> redEvery item must be a string: ", ".join([1, 2]) is a TypeError. Turn numbers into strings first.
Stripping spaces
Users type extra spaces more often than you'd think. strip returns the string without spaces at its start and its end; the spaces in between stay:
answer = " yes please "
print("[" + answer + "]")
print("[" + answer.strip() + "]")
print(answer.strip() == "yes please")
[ yes please ]
[yes please]
Truesplit and join together make a handy pair. split() without an argument ignores any number of spaces between words, so " ".join(text.split()) turns any messy spacing into single spaces.