How to split a string by using [] in Python

python split string by character
string split python
python split multiple delimiters
python split string by space
python split string by character count
python split word into letters
python split regex
python split string by comma into list

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?

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

Python String split() Method, Python String split() Method​​ The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one. Here's how to split strings by delimiters, line breaks, regular expressions, and the number of characters in Python. See the following post for details of string concatenation. Use split () method to split by single delimiter. If the argument is omitted, it will be separated by whitespace. Whitespace include spaces, newlines and tabs \t, and

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"

Python string split() example, How do I split a string into multiple delimiters in Python? Python string method split () returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num. Following is the syntax for split () method − str.split (str="", num=string.count (str)). str − This is any delimeter, by default it is space.

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

Python – How to split a String – Mkyong.com, () , you need to be a bit careful should the regular expression pattern involve a capture group enclosed in parentheses. If capture groups are used, then the matched text is also included in the result. # followed by any amount of extra whitespace. Hi everyone, in this Python Split String By Character tutorial, we will learn about how to split a string in python. Splitting string means breaking a given string into list of strings. Splitting string is a very common operation, especially in text based environment like – World Wide Web or operating in a text file.

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

Python String split() Method, Python – How to split a String. Split by whitespace. By default, split() takes whitespace as the delimiter. alphabet = "a b c d e f g" data = alphabet.split() #split string into a list for temp in data: print temp. Split + maxsplit. Split by first 2 whitespace only. Split by # Yet another example. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. How to split a string by using [] in Python. Ask

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

How to use Split in Python, Python String split() Method - Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left  To do this, you use the split function. What it does is split or breakup a string and add the data to a string array using a defined separator. If no separator is defined when you call upon the function, whitespace will be used by default. In simpler terms, the separator is a defined character that will be placed between each variable.

Python String split(), How to use Split in Python. At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of  split () method returns a list of strings after breaking the given string by the specified separator. separator : The is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator. maxsplit : It is a number, which tells us to split the string into maximum of provided number of times.

Split string at delimiter '\' in python, The split() method breaks up a string at the specified separator and returns a list of strings. Given a string, write a Python program to split the characters of the given string into a list. This approach uses for loop to convert each character into a list. Just enclosing the For loop within square brackets [] will split the characters of word into list. Python provides direct typecasting of string into list using list ().

How to use Split in Python, Instead it returns error : SyntaxError: EOL while scanning string literal . What is with character '\' in python. With any other character it works fine. be aware that using def split() will overload the python function split() – Mausy5043 Jul 7 '18 at 14:30 3 @Mausy5043 There's no builtin split in Python, maybe you have it confused with str.split method?

Comments
  • 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!" :)
  • Still no need for a regex. All that punctuation offends my eyes!
  • Haha - I thought the same exact thing @Torsten
  • 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.
  • Nice! Now write one for "matrix[0][1][2]"
  • heh! [subscript.rstrip(']') for subscript in 'matrix[0][1][2]'.split('[')[1:]]. Next! ;-)
  • Prior art by bobince and please don't use the keyword "str" for variable names!
  • Wrong - str.split takes a string of any length
  • I think Tyson was saying that str.split("[]") will split on the entire paramter i.e. "[]" and not "[" "]" individually. Nothing wrong with his answer.
  • "str" is a keyword in Python, so you should avoid using it as a variable name in examples!