views:

1213

answers:

8

So from this string:

"name[id]"

I need this:

"id"

I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?

+11  A: 

Use a regular expression:

import re 
s = "name[id]"
re.find(r"\[(.*?)\]", s).group(1) # = 'id'

str.split() takes a string on which to split input. For instance:

"i,split,on commas".split(',') # = ['i', 'split', 'on commas']

The re module also allows you to split by regular expression, which can be very useful, and I think is what you meant to do.

import re
s = "name[id]"

# split by either a '[' or a ']'
re.split('\[|\]', s) # = ['name', 'id', '']
Triptych
In all the time I've spent on SO, this is the first question where I thought "Use a regex!" instead of "Oh my good, don't use a regex for THIS!" :)
Torsten Marek
Still no need for a regex. All that punctuation offends my eyes!
bobince
Haha - I thought the same exact thing @Torsten
Triptych
+1 for use a regex!
epochwolf
This shouldn't be using a lazy dot. Try r"\[([^][]+)\]" instead to reduce backtracking. (Yes, it looks weird, but it works.) It probably won't matter much on such short strings, but the lazy dot is a bad habit.
Ben Blank
+3  A: 

Either

"name[id]".split('[')[:-1] == "id"

or

"name[id]".split('[')[1].split(']')[0] == "id"

or

re.search(r'\[(.*?)\]',"name[id]").group(1) == "id"

or

re.split(r'[\[\]]',"name[id]")[1] == "id"
MizardX
A: 

str.split uses the entire parameter to split a string. Try:

str.split("[")[1].split("]")[0]
Tyson
Wrong - str.split takes a string of any length
Triptych
I think Tyson was saying that str.split("[]") will split on the entire paramter i.e. "[]" and not "[" "]" individually. Nothing wrong with his answer.
Alinium
+3  A: 

Yes, the delimiter is the whole string argument passed to split. So your example would only split a string like 'name[]id[]'.

Try eg. something like:

'name[id]'.split('[', 1)[-1].split(']', 1)[0]

'name[id]'.split('[', 1)[-1].rstrip(']')
bobince
Nice! Now write one for "matrix[0][1][2]"
Triptych
heh! [subscript.rstrip(']') for subscript in 'matrix[0][1][2]'.split('[')[1:]]. Next! ;-)
bobince
A: 

I'm not a fan of regex, but in cases like it often provides the best solution.

Triptych already recommended this, but I'd like to point out that the ?P<> group assignment can be used to assign a match to a dictionary key:

>>> m = re.match(r'.*\[(?P<id>\w+)\]', 'name[id]')
>>> result_dict = m.groupdict()
>>> result_dict
{'id': 'id'}
>>>
monkut
A: 

You don't actually need regular expressions for this. The .index() function and string slicing will work fine.

Say we have:

>>> s = 'name[id]'

Then:

>>> s[s.index('[')+1:s.index(']')]
'id'

To me, this is easy to read: "start one character after the [ and finish before the ]".

John Fouhy
A: 
def between_brackets(text):
    return text.partition('[')[2].partition(']')[0]

This will also work even if your string does not contain a […] construct, and it assumes an implied ] at the end in the case you have only a [ somewhere in the string.

ΤΖΩΤΖΙΟΥ
A: 

I'm new to python and this is an old question, but maybe this?

str.split('[')[1].strip(']')

a3ot