Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将字符串从特定字符分割到特定字符_Python_String - Fatal编程技术网

Python:将字符串从特定字符分割到特定字符

Python:将字符串从特定字符分割到特定字符,python,string,Python,String,我使用Python 3.7.4 我想知道,如何拆分字符串,例如 0-12+65+89+19#1-23+43+1+2, 所以我得到了-后面的数字,介于+之间,直到两个#之间, 然后将数字(作为字符串)放入列表中,例如在本例中 ['12'、'65'、'89'、'19'] 有人能告诉我怎么做吗 还有,有没有办法做同样的事情,只是用“##”后面的部分? 有人能展示吗 这里有一种只使用stringsplit的方法: s.split('-')[1].rstrip('#').split('+') 其中,s是

我使用Python 3.7.4

我想知道,如何拆分字符串,例如
0-12+65+89+19#1-23+43+1+2
, 所以我得到了
-
后面的数字,介于
+
之间,直到两个
#
之间, 然后将数字(作为字符串)放入列表中,例如在本例中
['12'、'65'、'89'、'19']

有人能告诉我怎么做吗

还有,有没有办法做同样的事情,只是用“##”后面的部分?
有人能展示吗

这里有一种只使用string
split
的方法:

s.split('-')[1].rstrip('#').split('+')
其中,
s
是您的字符串

示例

s = "0-12+65+89+19##"

print(s.split('-')[1].rstrip('#').split('+'))
# ['12', '65', '89', '19']

这适合你的需要吗?此方法使用注释中建议的正则表达式

import re
text = "0-12+65+89+19##"
text=text.split("##")
text=text[0].split("-")
the_list = re.findall(r'\d+', text[1])
print(the_list)
结果是
['0','12','65','89','19']

In [1]:  mystr="0-12+65+89+19##"                                                                                                             

In [2]:  next((s for s in mystr.split('-') if s.endswith('##'))).rstrip('##').split('+')                                                     
Out[2]: ['12', '65', '89', '19']

将首先使用
-
进行拆分,然后从结果列表中找到以
##
结尾的字符串,并在
+

上拆分该字符串。如果您希望使用正则表达式并访问3.6,则可以使用以下方法:

>>> import regex as re
>>> text = "0-12+65+89+19##"
>>> re.search('-((\d+)\+?)*##', text)
>>> m.captures(2)
['12', '65', '89', '19']

正常的
re
模块不会为重复组提供多个捕获,因此请记住这一点。

您可以使用正则表达式来实现

import re

pattern = re.compile(r'([0-9]+)[^-]')  # find number groups after `-` character
result = re.findall(pattern, '0-12+65+89+19##')

# result = ['12', '65', '89', '19']

有很多方法可以做同样的事情,如果字符串以##结尾,那么

因此,在这个更新的问题中,您可以使用

s[s.find('-')+1:s.find('#')].split('+')

您最好使用
regex
来尝试此操作。在这种情况下,只需对原始字符串.True执行
re.findall(r'\d+',text)
。我从他的“拆分字符串”中假设,他可能在一个较长字符串的上下文中以双哈希进行拆分。看看他的预期结果。@johnplatenborough更新了有关最新更新的答案
s[s.find('-')+1:s.find('#')].split('+')