为了账号安全,请及时绑定邮箱和手机立即绑定

如何在不使用正则表达式的情况下删除 -> 之后的字符

如何在不使用正则表达式的情况下删除 -> 之后的字符

炎炎设计 2023-12-12 21:31:07
给定一个字符串 s 表示在编辑器中键入的字符,其中“->”表示删除,返回编辑器的当前状态。对于每一个“->”,它应该删除一个字符。如果有两个“->”,即“->->”,则应删除该符号后的 2 个字符。实施例1Inputs = "a->bcz"Output"acz"解释“b”被删除删除了。实施例2Input s = "->x->z"Outputempty string解释所有字符均被删除。另请注意,当编辑器为空时,您也可以键入删除。“”“我尝试过以下功能,但 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])在不使用正则表达式的情况下如何完成此操作?
查看完整描述

3 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

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


>>> 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'

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


查看完整回答
反对 回复 2023-12-12
?
繁花如伊

TA贡献2012条经验 获得超12个赞

这是一个简单的递归解决方案 -


# Constant storing the length of the arrow

ARROW_LEN = len('->')


def delete_forward(s: str):

    try:

        first_occurence = s.index('->')

    except ValueError:

        # No more arrows in string

        return s

    if s[first_occurence + ARROW_LEN:first_occurence + ARROW_LEN + ARROW_LEN] == '->':

        # Don't delete part of the next arrow

        next_s = s[first_occurence + ARROW_LEN:]

    else:

        # Delete the character immediately following the arrow

        next_s = s[first_occurence + ARROW_LEN + 1:]

    return delete_forward(s[:first_occurence] + s[first_occurence + ARROW_LEN + 1:])

请记住,Python 字符串是不可变的,因此您应该依赖字符串切片来创建新字符串。


在每个递归步骤中,都会找到 的第一个索引->,并提取出在此之前的所有内容。然后,检查当前位置后是否有另一个->紧随其后的字符 - 如果有,请勿删除下一个字符并delete_forward在第一次出现后调用所有内容。如果紧随其后的不是箭头,则删除当前箭头之后紧邻的下一个字符,并将其送入delete_forward。


这将x->zb变成xb.


递归的基本情况是.index找不到匹配项,在这种情况下返回结果字符串。


输出

>>> delete_forward('ab->cz')        

'abz'

>>> delete_forward('abcz')   

'abcz'

>>> delete_forward('->abc->z')

'bc'

>>> delete_forward('abc->z->')   

'abc'

>>> delete_forward('a-->b>x-->c>de->f->->g->->->->->')

'a->x->de'


查看完整回答
反对 回复 2023-12-12
?
慕的地10843

TA贡献1785条经验 获得超8个赞

在 python 中可以有多种方法来实现这一点,例如:


使用拆分和列表推导式(如果您想在每次遇到一个或多个删除字符时删除单个字符):

def delete_forward(s):

    return ''.join([s.split('->')[0]] + [i[1:] if len(i)>1 else "" for i in s.split('->')[1:]])

现在delete_forward("a->bcz")返回'acz'&delete_forward("->x->z")返回''。请注意,这适用于每种可能的情况,无论是否有许多删除字符,一个或根本没有。此外,只要输入是,它就永远不会抛出任何异常或错误str。然而,这假设您每次遇到一个或多个删除字符时都希望删除单个字符。


如果要删除与删除字符发生次数一样多的字符:

def delete_forward(s):

    new_str =''

    start = 0

    for end in [i for i in range(len(s)) if s.startswith('->', i)] +[len(s)+1]:

        new_str += s[start:end]

        count = 0

        start = max(start, end)

        while s[start:start+2] =='->':

            count+=1

            start+=2

        start += count

    return new_str

对于上述两种情况,这会产生相同的输出,但是对于 case: 'a->->bc',它会产生'a'而不是'ac'第一个函数产生的输出。


查看完整回答
反对 回复 2023-12-12
  • 3 回答
  • 0 关注
  • 53 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信