Perl to Python again

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Fri Mar 11 19:04:58 EST 2016


On Friday, March 11, 2016 at 3:42:36 PM UTC-8, Fillmore wrote:
> So, now I need to split a string in a way that the first element goes 
> into a string and the others in a list:
> 
> while($line = <STDIN>) {
> 
>      my ($s, at values)  = split /\t/,$line;
> 
> I am trying with:
> 
> for line in sys.stdin:
>      s,values = line.strip().split("\t")
>      print(s)
> 
> but no luck:
> 
> ValueError: too many values to unpack (expected 2)
> 
> What's the elegant python way to achieve this?
> 
> Thanks

I'd call the split, assign it to a temp value, then pull from there, like this:

parts = line.strip().split('\t')
s = parts[0]
values = parts[1:]

There might be a one-line way to do it, but I can't think of one that doesn't rely on calling split() twice.



More information about the Python-list mailing list