【问题标题】:Find and cut out a python substring查找并剪切一个 python 子字符串
【发布时间】:2013-07-08 05:03:56
【问题描述】:
这是我想要做的:
我的字符串很长:
s = asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf
我想剪掉子串:iwanttocutthisout
我将遍历一个循环,每次迭代时 s 的值都会改变。唯一在每次迭代中保持不变的是要剪切的子字符串的开始和结束:iwant 和 thisout。
给定这些参数,我如何截取子字符串?
感谢您的帮助!
【问题讨论】:
标签:
python
string
find
substring
cut
【解决方案1】:
您可以分别在 iwant(+len(iwant) 到 dis-include iwant)和 thisout 的出现索引之间进行切片,如下所示:
>>> s = "asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf"
>>> s[s.index("iwant")+len("iwant"):s.index("thisout")]
'tocut'
图表:
"asdf23rlkasdfids(iwanttocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
^ ^
| |
index("iwant") |
index("thisout")
注意这两个索引(包括开头)之间的切片将如何得到iwanttocut。添加len("iwant") 会导致:
"asdf23rlkasdfidsiwant(tocut)thisoutsadlkljasdfhvaildufhblkajsdhf"
^ ^
/----| |
index("iwant") |
index("thisout")
【解决方案2】:
像这样在re 模块中使用sub() 函数:
clean_s = re.sub(r'iwant\w+thisout','',s)
如果您希望字符串中包含非单词字符,请用 \w+ 替换 .+,如果开始和结束标记之间可能没有任何额外字符(即 '我想要这个')
【解决方案3】:
s = s.replace('iwantthisout', '')