Splitting and joining in Python
Round-tripping between strings and lists of pieces.
sentence = "never gonna give you up"
words = sentence.split()
csv_row = "ada,grace,katherine"
names = csv_row.split(",")
rejoined = " ".join(words)
path = "/".join(["usr", "local", "bin"])
lines = "one\ntwo\nthree".splitlines()
first, _, rest = sentence.partition(" ")
slug = "-".join(sentence.split())
How it works
splitbreaks on whitespace or any separator.joinis the inverse: the glue string comes first.splitlinesandpartitionhandle common special cases.
The run, in numbers
- Lines
- 12
- Characters to type
- 305
- Tokens
- 98
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 65 seconds.
Step 4 of 9 in Strings, step 10 of 72 in Language basics.