如何在字符串再次出现之前拆分字符串?

2024-04-27 22:52:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有字符串NYKMIANYKCLE,我想把它拆分成一个只有NYKMIANYKCLE(在'NYK'第二次出现之前拆分)的列表。有没有用python实现的方法


Tags: 方法字符串列表nyknykmianykmianykclenykcle
3条回答

可以使用^{}查找以NYK开头、不包含另一个NYK或后跟字符串结尾的所有子字符串:

>>> s = 'NYKMIANYKCLE'
>>> import re
>>> re.findall(r'NYK.+?(?=NYK|$)', s)
['NYKMIA', 'NYKCLE']

第一个?确保搜索是非贪婪的;一次一个子串,而(?=NYK|$)强制断言该子串在下一个NYK...子串或字符串的结尾$之前


更多测试:

>>> s = 'NYKMIANYKCLENYKjahsja'
>>> re.findall(r'NYK.+?(?=NYK|$)', s)
['NYKMIA', 'NYKCLE', 'NYKjahsja']

因为问题是关于拆分的,所以可以使用新的regex module, 允许零宽度字符进行拆分

import regex
s='NYKMIANYKCLE'
print(regex.split('(?V1)(?=NYK)',s))

输出

['', 'NYKMIA', 'NYKCLE']

更新

以避免在行首分裂

print(regex.split('(?V1)[^^](?=NYK)',s))

输出

['NYKMI', 'NYKCLE']

解释

(?V1)      #Forces new version 2 of split which allows zero width chars for split
[^^]       #don't take line beginning as split
(?=NYK)    #take a position as split if the position is followed by NYK

您可以尝试以下方法:

string = 'NYKMIANYKCLE'
substring = 'NYK'

first_index = string.index(substring)
second_index = string.index(substring, first_index + len(substring))
print string[:second_index], string[second_index:]

相关问题 更多 >