python – How to split a string by multiple delimiters at once?

Question:

import re
s = input().split()
print(re.split('?|&',s))

It does not work this way, displays a bunch of incomprehensible errors.

You need to split the string by characters: ? or &

For example, some URL string is given:

https://yandex.ru/images/search?text=котики&source=images_drawing

Answer:

Example:

In [84]: re.split(r"[?&]", url)
Out[84]: ['https://yandex.ru/images/search', 'text=котики', 'source=images_drawing']

but it's still better to use urllib.parse :

In [85]: from urllib.parse import urlparse, parse_qs, parse_qsl

In [86]: parse_qs(urlparse(url).query)
Out[86]: {'text': ['котики'], 'source': ['images_drawing']}

In [89]: parse_qsl(urlparse(url).query)
Out[89]: [('text', 'котики'), ('source', 'images_drawing')]
Scroll to Top