如果出现符号,将单词(字符串)的一部分更改为另一个字符串。python

如果出现符号,将单词(字符串)的一部分更改为另一个字符串。python,python,Python,如果出现字符“=”,我如何最有效地剪切单词的一部分,然后如果出现字符“=”,则完成剪切单词?例如: 从一根大绳上 '321@5=85@45@41=#=I-LOVE-STACK-OVER-FLOW=#=3234@41@=q#$^1=@=xx$q=@=xpa$=4319' python代码返回: 'I-LOVE-STACK-OVER-FLOW' 任何帮助都将不胜感激。使用split(): 使用regex: import re s = '321@5=85@45@41=#=I-LOVE-STACK-

如果出现字符“
=
”,我如何最有效地剪切单词的一部分,然后如果出现字符“
=
”,则完成剪切单词?例如:

从一根大绳上

'321@5=85@45@41=#=I-LOVE-STACK-OVER-FLOW=#=3234@41@=q#$^1=@=xx$q=@=xpa$=4319'
python代码返回:

'I-LOVE-STACK-OVER-FLOW'
任何帮助都将不胜感激。

使用
split()

使用
regex

import re
s = '321@5=85@45@41=#=I-LOVE-STACK-OVER-FLOW=#=3234@41@=q#$^1=@=xx$q=@=xpa$=4319'

print(re.search('%s(.*)%s' % (st, ed), s).group(1))
输出

I-LOVE-STACK-OVER-FLOW
使用
split()

使用
regex

import re
s = '321@5=85@45@41=#=I-LOVE-STACK-OVER-FLOW=#=3234@41@=q#$^1=@=xx$q=@=xpa$=4319'

print(re.search('%s(.*)%s' % (st, ed), s).group(1))
输出

I-LOVE-STACK-OVER-FLOW

除了@DirtyBit的答案外,如果您还想处理超过2'=#='的情况,可以拆分字符串,然后每隔一个元素添加一个:

s = '321@5=85@45@41=#=I-LOVE-STACK-OVER-FLOW=#=3234@41@=q#$^1=@=xx$q=@=xpa$=4319=#=|I-ALSO-LOVE-SO=#=3123123'
parts = s.split('=#=')
print(''.join([parts[i] for i in range(1,len(parts),2)]))
输出
除了@DirtyBit的答案外,如果您还想处理超过2'=#='的情况,可以拆分字符串,然后每隔一个元素添加一个:

s = '321@5=85@45@41=#=I-LOVE-STACK-OVER-FLOW=#=3234@41@=q#$^1=@=xx$q=@=xpa$=4319=#=|I-ALSO-LOVE-SO=#=3123123'
parts = s.split('=#=')
print(''.join([parts[i] for i in range(1,len(parts),2)]))
输出
代码中有解释

import re


ori_list = re.split("=#=",ori_str)
    # you can imagine your goal is to find the string wrapped between signs of "=#=" 
    # so after the split, the even number position must be the parts outsides of "=#=" 
    # and the odd number position is what you want
for i in range(len(ori_list)):
    if i%2 == 1:#odd position
       print(ori_list[i])

代码中有解释

import re


ori_list = re.split("=#=",ori_str)
    # you can imagine your goal is to find the string wrapped between signs of "=#=" 
    # so after the split, the even number position must be the parts outsides of "=#=" 
    # and the odd number position is what you want
for i in range(len(ori_list)):
    if i%2 == 1:#odd position
       print(ori_list[i])