Skip to content

Latest commit

 

History

History
25 lines (17 loc) · 1.06 KB

20240109154653.md

File metadata and controls

25 lines (17 loc) · 1.06 KB

Two ways to split on last delimiter

In Python you can use rpartition() or rsplit() to split a string starting at the end.

In this example we use both to split domains by sub vs main.

rpartition() keeps the delimiter in the results, rsplit() does not, but it requires its optional "maxsplit" argument to limit the amount of splits.

>>> domains = ["pybit.es", "codechalleng.es", "shop.pybit.es", "something.longer.pybit.es"]

# this gives me different sized lists 🤔
>>> [domain.split(".") for domain in domains]
[['pybit', 'es'], ['codechalleng', 'es'], ['shop', 'pybit', 'es'], ['something', 'longer', 'pybit', 'es']]

# rpartition() for the win:
>>> [domain.rpartition(".") for domain in domains]
[('pybit', '.', 'es'), ('codechalleng', '.', 'es'), ('shop.pybit', '.', 'es'), ('something.longer.pybit', '.', 'es')]

# to clean up the dot you can also split from the end, but then we need to limit it to 1
>>> [domain.rsplit(".", maxsplit=1) for domain in domains]
[['pybit', 'es'], ['codechalleng', 'es'], ['shop.pybit', 'es'], ['something.longer.pybit', 'es']]

#strings