【问题标题】: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', '')
      

      【讨论】:

        猜你喜欢
        • 2023-03-14
        • 2017-11-29
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2017-03-10
        • 2015-07-29
        相关资源
        最近更新 更多