首页 > 解决方案 > 如何在不使用正则表达式的情况下删除 -> 之后的字符

问题描述

给定一个字符串 s 表示输入到编辑器中的字符,“->”表示删除,返回编辑器的当前状态。对于每一个“->”,它应该删除一个字符。如果有两个“->”,即“->->”,则应删除符号后的 2 个字符。

示例 1

Input
s = "a->bcz"
Output
"acz"

解释

“b”被删除删除了。

示例 2

Input 
s = "->x->z"
Output
empty string

解释

所有字符都被删除。另请注意,您也可以在编辑器为空时键入 delete。""" 我尝试了以下功能,但 id 没有工作

def delete_forward(text):
"""
return the current state of the editor after deletion of characters 
"""
f = "->"
for i in text:
    if (i==f):
        del(text[i+1])

我怎样才能在不使用正则表达式的情况下完成这个?

标签: python

解决方案


字符串不支持项目删除。您必须创建一个新字符串。

>>> astring = 'abc->def'
>>> astring.index('->')  # Look at the index of the target string
3
>>> x=3
>>> astring[x:x+3]  # Here is the slice you want to remove
'->d'
>>> astring[0:x] + astring[x+3:]  # Here is a copy of the string before and after, but not including the slice
'abcef'

这仅处理每个字符串一个“->”,但您可以对其进行迭代。


推荐阅读