[Tutor] multiple assignment

Kent Johnson kent37 at tds.net
Tue Oct 18 12:25:41 CEST 2005


Vincent Gulinao wrote:
> I was fascinated when I learned that I can do this in Python:
> 
> (str1, str2, str3, rest) = str.split(" ", 3)
> 
> Later that I realize that str could contain values of less than 4 
> strings, in which case it would complain something like -- ValueError: 
> unpack list of wrong size.
> 
> Now I don't want to spoil the fun.
> 
> In essence, I'd like to capture the first 3 words in a string. If str is 
> less than 3 words then any or all of the containers could have a None value.

AFAIK there is no pretty solution but this works:
str1, str2, str3 = (s.split(" ", 3) + [None]*3)[:3]

Kent



More information about the Tutor mailing list