Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am looking to split strings at "(", this is working fine if there is only one "(" character in the string. However, if there are more than one such character, it throws a value error too many values to unpack

data = 'The National Bank (US) (Bank)'

I've tried the below code:

name, inst = data.split("(")

Desired output:

name = 'The National Bank (US)'
inst = '(Bank)'
question from:https://stackoverflow.com/questions/65940592/too-many-values-to-unpack-expected-2-while-splitting-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
488 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your split method is splitting the input on both ( characters, giving you the result:

["The National Bank ", "US) ", "Bank)"]

You are then attempting to unpack this list of three values into two variables, name and inst. This is what the error "Too many values to unpack" means.

You can restrict the number of splits to be made using the second parameter to split, but this will give you the wrong result as well.

You actually want to split from the right of the string, on the first space character. You can do that with rsplit:

data = 'The National Bank (US) (Bank)'
name, inst = data.rsplit(' ', 1)

name and inst will now be set as you expect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...