Perl to Python again

Martin A. Brown martin at linux-ip.net
Fri Mar 11 19:12:27 EST 2016


Good afternoon Fillmore,

> 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)

That means that the number of items on the right hand side of the 
assignment (returned from the split() call) did not match the number 
of variables on the left hand side.

> What's the elegant python way to achieve this?

Are you using Python 3?

  s = 'a,b,c,d,e'
  p, *remainder = s.split(',')
  assert isinstance(remainder, list)

Are you using Python 2?

  s = 'a,b,c,d,e'
  remainder = s.split(',')
  assert isinstance(remainder, list)
  p = remainder.pop(0)

Aside from your csv question today, many of your questions could be 
answered by reading through the manual documenting the standard 
datatypes (note, I am assuming you are using Python 3).

  https://docs.python.org/3/library/stdtypes.html

It also sounds as though you are applying your learning right away.  
If that's the case, you might also benefit from reading through all 
of the services that are provided in the standard library with 
Python:

  https://docs.python.org/3/library/

In terms of thinking Pythonically, you may benefit from:

  The Python Cookbook (O'Reilly)
  http://shop.oreilly.com/product/0636920027072.do

  Python Module of the Week
  https://pymotw.com/3/

I'm making those recommendations because I know and have used these 
and also because of your Perl background.

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/



More information about the Python-list mailing list