如何在 Python 中使用 [] 拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/514029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:16:18  来源:igfitidea点击:

How to split a string by using [] in Python

pythonstring

提问by Joan Venge

So from this string:

所以从这个字符串:

"name[id]"

“名称[id]”

I need this:

我需要这个:

"id"

“ID”

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

我使用了 str.split('[]'),但是没有用。它只需要一个分隔符吗?

回答by Triptych

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:

str.split()需要一个字符串来分割输入。例如:

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

The remodule also allows you to split by regular expression, which can be veryuseful, and I think is what you meant to do.

re模块还允许您通过正则表达式进行拆分,这非常有用,我认为这就是您的意思。

import re
s = "name[id]"

# split by either a '[' or a ']'
re.split('\[|\]', s) # = ['name', 'id', '']

回答by Markus Jarderot

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"

回答by bobince

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

是的,分隔符是传递给 split 的整个字符串参数。所以你的例子只会拆分像'name[]id[]'这样的字符串。

Try eg. something like:

尝试例如。就像是:

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

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

回答by monkut

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:

Triptych 已经推荐了这个,但我想指出 ?P<> 组分配可用于将匹配项分配给字典键:

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

回答by John Fouhy

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

您实际上不需要为此使用正则表达式。.index() 函数和字符串切片将正常工作。

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

对我来说,这很容易理解:“在 [ 之后开始一个字符并在 ] 之前结束”。

回答by tzot

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.

即使您的字符串不包含[…]构造,这也将起作用,并且在字符串中]只有[某个位置的情况下,它假定末尾是隐含的。

回答by a3ot

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

我是 python 新手,这是一个老问题,但也许是这个?

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

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

回答by Ryosuke Hujisawa

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

您可以使用 [] 获取列表的值。例如,从 URL 中创建一个列表,如下所示,使用 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

如果您只想从这个列表中获得“http”的价值怎么办?你可以这样使用

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

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

或者,如果您只想从该列表中获取值“1”怎么办?你可以这样使用

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

回答by Tyson

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

str.split 使用整个参数来拆分字符串。尝试:

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