Skip to content

Instantly share code, notes, and snippets.

@jrmontag
Last active September 21, 2022 12:07
Show Gist options
  • Save jrmontag/957b4bb8f4b89d5006a8 to your computer and use it in GitHub Desktop.
Save jrmontag/957b4bb8f4b89d5006a8 to your computer and use it in GitHub Desktop.
split a string at every nth occurrence of a delimiter (here, a pipe) in Python
import re
s = 'id|tag1|id|tag2|id|tag3|id|tag4'
# nb: escaping | (delimiter) necessary *outside* of character set ( [] ), not inside
print re.findall("[^|]+\|[^|]+", s)
# ['id|tag1', 'id|tag2', 'id|tag3', 'id|tag4']
n=3
print re.findall("\|".join(["[^|]+"]*n), s)
# ['id|tag1|id', 'tag2|id|tag3']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment