Reputation:
I recently started working with Python and I am trying to split a string in Python and then extract only fields from that list.
Below is my node string and it will always be of four words separated by /
.
node = "/tt/pf/test/v1"
I am trying to split above string on /
and then store test
and v1
value from it in some variable -
Below is what I have tried -
node = "/tt/pf/test/v1"
a,b,c,d = node.split("/")
print c
print d
Below is the error I got -
ValueError: too many values to unpack
Upvotes: 6
Views: 8735
Reputation: 29804
You're not taking into the account the empty string generated by the first / character:
node = "/tt/pf/test/v1"
node.split('/')
['', 'tt', 'pf', 'test', 'v1']
A quick fix can be this:
_,a,b,c,d = node.split("/")
or slice the split()
result:
a,b,c,d = node.split("/")[1:]
Upvotes: 6
Reputation: 11
node.split("/")
['', 'tt', 'pf', 'test', 'v1']
First one counts as an empty word. Try: skip,a,b,c,d = node.split("/")
Upvotes: 0
Reputation: 78630
This divides it into 5 values, not 4, because it includes the empty string before the /
at the start.
node.split("/")
# ['', 'tt', 'pf', 'test', 'v1']
Try:
empty,a,b,c,d = node.split("/")
Upvotes: 0