Not enough values to unpack, spliting str s
Question:
I tried this, and got this, I can’t explain, why happened?
str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)
Answers:
You would need to enter three strings separated by spaces. I’m guessing you’re getting the error because you’re entering one string, and then hitting enter to type another, but then it gives the error.
So as input you would have to type "s1 s2 s3" and it would work. But if you just typed "s1" and hit enter it would give the not enough values error:
ValueError: not enough values to unpack (expected 3, got 1)
It would work only if you type exactly 3 words separated by whitespaces. For example: "a b c"
, "one two three"
and hit the Enter after this.
For a bit more robust code you can do
a,b,c,*overflow="one word too much and even more".split()
overflow=['much', 'and', 'even', 'more']
will hold all words if 4 or more were inserted, so you wont get an error message there.
It of course can’t handle not enough words, which result in ValueError: not enough values to unpack
More code but more logical for other readers – to also handle not enough values.
words = input().split()
if len(words) != 3:
raise ValueError("Not three words provided")
str1, str2, str3 = words
Instead if a ValueError you can also look how to handle that via a while loop until the condition is correct.
I tried this, and got this, I can’t explain, why happened?
str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)
You would need to enter three strings separated by spaces. I’m guessing you’re getting the error because you’re entering one string, and then hitting enter to type another, but then it gives the error.
So as input you would have to type "s1 s2 s3" and it would work. But if you just typed "s1" and hit enter it would give the not enough values error:
ValueError: not enough values to unpack (expected 3, got 1)
It would work only if you type exactly 3 words separated by whitespaces. For example: "a b c"
, "one two three"
and hit the Enter after this.
For a bit more robust code you can do
a,b,c,*overflow="one word too much and even more".split()
overflow=['much', 'and', 'even', 'more']
will hold all words if 4 or more were inserted, so you wont get an error message there.
It of course can’t handle not enough words, which result in ValueError: not enough values to unpack
More code but more logical for other readers – to also handle not enough values.
words = input().split()
if len(words) != 3:
raise ValueError("Not three words provided")
str1, str2, str3 = words
Instead if a ValueError you can also look how to handle that via a while loop until the condition is correct.