I’m new to Python and struggling to solve the following issue the most Pythonic way.
I have a string (Example states given below) which needs to be split (.split('/', 2)) and appointed (up) to 3 variables (vars. a, b and c). The string is a URL which I need to split into 3 segments.
The string and its segments can be the following examples:
- ‘seg_a/seb_b/the_rest’
-> a = seg_a, b = seg_b, c = the_rest - ‘seg_a/the_rest’
-> a = seg_a, b = None, c = the_rest - ‘seg_a’
-> a = seg_a, b = None, c = None
Note: No obligation exists to have None value given if nothing else gets appointed. They simple may not exist (b in ex. 2, b and c in ex. 3).
If split results in 1 item, it’s given to variable a.
If split results in 2 items, it’s given to variable a and c
If split results in 3 items, then it’s segments are given to variables a, b and c
I have found 2 methods achieving this, both seem not Pythonic, hence resulting in this question.
Method A:
Split.
Count.
Depending on count, appoint segments to variables with IF.. Elif.. Elif.. Else. statement
Method B:
Use list comprehension and nested Try-Except blocks. Ex:
try:
a, b, c = [i for i in to_split.split("/", 2)]
except ValueError:
try:
a, c = [i for i in to_split.split("/", 1)]
b = None
except ValueError:
a = to_split
b, c = None, None
My question (short):
- What is the correct, Pythonic way of splitting this string to its
segments and appointing them to variables a, b and c?
I would do: