Mehdi
Mehdi

Reputation: 1525

Split string with delimiters in Python

I have such a String as an example:

"[greeting] Hello [me] my name is John."

I want to split it and get such a result

('[greetings]', 'Hello' , '[me]', 'my name is John')

Can it be done in one line of code?

OK another example as it seems that many misunderstood the question.

"[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."

then I should get

 ('[greetings]', ' Hello my friends ' , '[me]', ' my name is John. ', '[bow]', ' nice to meet you.')

I basically want to send this kind of string to my robot. It will automatically decompose it and do some motion corresponding to [greetings] [me] and [bow] and in between speak the other strings.

Upvotes: 0

Views: 481

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

Using regex:

>>> import re
>>> s = "[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
>>> re.findall(r'\[[\w\s.]+\]|[\w\s.]+', s)
['[greeting]', ' Hello my friends ', '[me]', ' my name is John. ', '[bow]', ' nice to meet you.']

Edit:

>>> s =  "I can't see you"
>>> re.findall(r'\[.*?\]|.*?(?=\[|$)', s)[:-1]
["I can't see you"]
>>> s = "[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
>>> re.findall(r'\[.*?\]|.*?(?=\[|$)', s)[:-1]
['[greeting]', ' Hello my friends ', '[me]', ' my name is John. ', '[bow]', ' nice to meet you.'

Upvotes: 1

zzantares
zzantares

Reputation: 350

I think can't be done in one line, you need first split by ], then [:

# Run in the python shell
sentence = "[greeting] Hello [me] my name is John."
for part in sentence.split(']')
  part.split('[')

# Output
['', 'greeting']
[' Hello ', 'me']
[' my name is John.']

Upvotes: 0

royhowie
royhowie

Reputation: 11171

The function you're after is .split(). The function accepts a delimiter as its argument and returns a list made by splitting the string at every occurrence of the delimiter. To split a string, using either "[" or "]" as a delimiter, you should use a regular expression:

import re
str = "[greeting] Hello [me] my name is John."
re.split("\]|\[", str)
# returns ['', 'greeting', ' Hello ', 'me', ' my name is John.']

This uses a regular expression to split the string.

\] # escape the right bracket
|  # OR
\[ # escape the left bracket

Upvotes: 1

Related Questions