Joan Venge
Joan Venge

Reputation: 331260

How to split a string by using [] in Python

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?

Upvotes: 2

Views: 16836

Answers (9)

Ryosuke Hujisawa
Ryosuke Hujisawa

Reputation: 2872

You can get the value of the list use []. For example, create a list from URL like below with split.

>>> urls = 'http://quotes.toscrape.com/page/1/'

This generates a list like the one below.

>>> print( urls.split("/") )
['http:', '', 'quotes.toscrape.com', 'page', '11', '']

And what if you wanna get value only "http" from this list? You can use like this

>>> print(urls.split("/")[0])
http:

Or what if you wanna get value only "1" from this list? You can use like this

>>> print(urls.split("/")[-2])
1

Upvotes: 0

Markus Jarderot
Markus Jarderot

Reputation: 89221

Either

"name[id]".split('[')[1][:-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"

Upvotes: 7

a3ot
a3ot

Reputation: 1

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

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

Upvotes: 0

tzot
tzot

Reputation: 95991

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.

Upvotes: 1

John Fouhy
John Fouhy

Reputation: 42193

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 ]".

Upvotes: 1

monkut
monkut

Reputation: 43860

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'}
>>>

Upvotes: 2

Tyson
Tyson

Reputation: 6244

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

str.split("[")[1].split("]")[0]

Upvotes: -1

Kenan Banks
Kenan Banks

Reputation: 212078

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', '']

Upvotes: 13

bobince
bobince

Reputation: 536577

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(']')

Upvotes: 3

Related Questions