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

2024-06-17 11:09:14 发布

您现在位置: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'

任何帮助都将不胜感激。你知道吗


Tags: 代码stack字符flow单词overxx绳子
3条回答

解释在代码中。你知道吗

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

除了@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)]))

输出

I-LOVE-STACK-OVER-FLOW|I-ALSO-LOVE-SO

使用split()

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

st = '=#='
ed = '=#='
print((s.split(st))[1].split(ed)[0])

使用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

相关问题 更多 >