Here's a puzzle...
Bengt Richter
bokr at accessone.com
Sat Jul 21 21:39:28 EDT 2001
On 21 Jul 2001 23:56:40 GMT, thedustbustr at aol.com (TheDustbustr) wrote:
>I'm trying to split the following string called data into four variables:
>
>:Angel PRIVMSG Wiz :here is my message!
>
>(so data=':Angel PRIVMSG Wiz :here is my message!') with an outcome of:
>
>sender='Angel'
>command='PRIVMSG'
>rcpt=Wiz'
>message='here is my message!'
>
>Unless my logic is flawed, this should return 'PRIVMSG':
>
>sender='Angel'
>print data[len(sender)+2:string.find(data[len(sender)+2:],' ')]
>
>It prints '' (an empty string). Is my logic flawed, or does Python dislike a
>string splice determined by a function?
>
No, Python likes it fine ;-)
>>> print data[len(sender)+2:string.find(data,' ',len(sender)+2)]
PRIVMSG
Your string.find was giving you an offset from the beginning of the slice you
were passing it, not starting the search in data at a given offset.
When a big expression doesn't work, try the sub-expressions separately to see
if you're getting what you expect. Usually it will become clear ;-)
E.g., to see the slice (not splice ;-) parameters you were using you could
just change the ';' to a comma and drop the 'data' to print it out as a list:
>>> print data[len(sender)+2:string.find(data[len(sender)+2:],' ')]
>>> print [len(sender)+2,string.find(data[len(sender)+2:],' ')]
[7, 7]
so you were doing print data[7:7] and getting what you asked for ;-)
looking at what string.find was operating on:
>>> data[len(sender)+2:]
'PRIVMSG Wiz :here is my message!'
01234567 -- guess where the second 7 in [7, 7] came from (not an offset into data)
>And if you are up to it, feel free to help me splice (correct terminology,
>parse?) for variables rcpt and message ;)
>
Not knowing the real grammar of your data string, here's a possibility:
>>> data=':Angel PRIVMSG Wiz :here is my message!'
>>> front,message = data.split(':')[1:]
>>> sender,command,rcpt = front.split()
>>>
>>> sender
'Angel'
>>> command
'PRIVMSG'
>>> rcpt
'Wiz'
>>> message
'here is my message!'
You could also do it with a regular expression.
The above rigidly depends on always having two colons and
always having three non-blank strings separated by white space
between the colons. (The [1:] throws away anything to the
left of the first colon).
For a better solution, post the detailed rules on the exact
character sequence in your data.
More information about the Python-list
mailing list