Splitting a string

Gary Herron gherron at islandtraining.com
Tue May 15 15:05:43 EDT 2007


HMS Surprise wrote:
> The string s below has single and double qoutes in it. For testing I
> surrounded it with triple single quotes. I want to split off the
> portion before the first \, but my split that works with shorter
> strings does not seem to work with this one.
>
> Ideas?
>
> Thanks,
> jvh
>
> s = ''''D132258\',\'\',
> \'status=no,location=no,width=630,height=550,left=200,top=100\')"
> target="_blank" class="dvLink" title="Send an Email to selected
> employee">'''
>
> t = s.split('\\')
>   
That can't work because there are no \'s in your string.   There are 
backslashes in your program to escape some of the characters from being 
meaningful to the python interpreter.  However, once the string is 
parsed and created, it has no backslashes in it.  To see this, just 
print it or use find on it:

 >>> s = ''''D132258\',\'\',
... \'status=no,location=no,width=630,height=550,left=200,top=100\')"
... target="_blank" class="dvLink" title="Send an Email to selected
... employee">'''
 >>> print s
'D132258','',
'status=no,location=no,width=630,height=550,left=200,top=100')"
target="_blank" class="dvLink" title="Send an Email to selected
employee">
 >>> s.find('\\')
-1

So the question now becomes:  Where do you really want to split it?  If 
at the comma then one of these will work for you:

 >>> print s.split(',')[0]
'D132258'

 >>> i = s.index(',')
 >>> print s[:i]
'D132258'


Gary Herron







More information about the Python-list mailing list