Last active
September 21, 2022 12:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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