[Zope] string module

Paul Winkler slinkp23@yahoo.com
Thu, 14 Jun 2001 12:28:24 -0400


Sebal wrote:
> 
> >On 13 Jun 2001 07:47:13 -0700, Sebal wrote:
> >> I have a method what from a "MULTIPART FORM" put a file named
> 'myFile.pdf'
> >> in a directory.
> >> And after i want the methood to create a Zclass instance[PDFclass] whith
> >> id=myFile.
> >>
> >> I tried  with split, join, and translate method of string module, and I
> >> can't get a valid id with split and join ; and with translate if 'myFile'
> is
> >> 'mypdf' (so the file is 'mypdf.pdf') I'll get 'my' as id for my PDFclass
> >> instance.
> >
> >
> >Split on the '.' not on 'pdf'.
> >
> >Example from the interpreter:
> >       >>> foo="mypdf.pdf"
> >       >>> id,extension = string.split(foo,'.')
              ^^^^^^^^^^^^^

You missed this part -- explained below.


> >       >>> print id
> >       mypdf
> >
> >Bill
> 
> This doesn't work:
> 1>>>mydtml_method.html:
> <dtml-call "REQUEST.set('filename' , 'test.pdf')" >
> <dtml-call "REQUEST.set('file_id' , _.string.split(filename,'.'))" >
> <dtml-var file_id>
> 
> with view I get ['test','pdf']
> 
> 2>>>mydtml_method.html:
> <dtml-call "REQUEST.set('filename' , 'test.pdf')" >
> <dtml-call "REQUEST.set('file_id' , _.string.split(filename,'.pdf'))" >
> <dtml-var file_id>
> 
> with view I get ['test','']
> 
> This make a invalide id for my PDFclass instance.
> I don't know how to separate the 2 arguments of file_id.

A quick Python lesson: In Bill's suggestion, this was done by assigning the
result to two variables, like so (an example at the python interactive prompt):

>>> foo="mypdf.pdf"
>>> id, extension = string.split(foo,'.')
>>> id
'mypdf'
>>> extension
''

You can do this with any sequence in python:

>>> stuff = (0, 1, 2)
>>> a, b, c = stuff

Now a is 0, b is 1, and c is 2.

This is called unpacking, and it's a common python technique for assigning the
contents of a list to a bunch of variables.

However, it only works if you assign to **exactly** as many variables as there
are in the sequence. In your situation, if the input does not contain exactly
one occurence of ".pdf", you'll get this error:

>>> id, extension = string.split("bob.pdf.pdf", ".pdf")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: unpack list of wrong size

>>> id, extension = string.split("bob", ".pdf")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: unpack list of wrong size

An error-proof way to deal with it would be to use a subscript to get the first
element from the output of split. This works whether split returns a list of one
item or of a million. We want to take element 0 from the sequence created by
splitting the input.

>>> id = string.split("bob.pdf.spam.pdf", ".pdf")[0]
>>> id
'bob'


Now let's put that into your example:

<dtml-call "REQUEST.set('filename' , 'test.pdf')" >
<dtml-call "REQUEST.set('file_id' ,
_.string.split(filename,'.pdf')[0])" >
<dtml-var file_id>