Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by using [] in Python

Tags:

python

string

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?

like image 724
Joan Venge Avatar asked Mar 13 '26 06:03

Joan Venge


2 Answers

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', '']
like image 143
Kenan Banks Avatar answered Mar 15 '26 19:03

Kenan Banks


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"
like image 40
Markus Jarderot Avatar answered Mar 15 '26 19:03

Markus Jarderot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!