typestar

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

  1. split breaks on whitespace or any separator.
  2. join is the inverse: the glue string comes first.
  3. splitlines and partition handle 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.

Type this snippet

Step 4 of 9 in Strings, step 10 of 72 in Language basics.

← Previous Next →