gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:45:19 25 4
gpt4 key购买 nike

给定一个字符串 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])
如何在不使用正则表达式的情况下完成此操作?

最佳答案

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

>>> 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'
这仅处理每个字符串一个 '->',但您可以对其进行迭代。

关于python - 如何在不使用正则表达式的情况下删除 -> 之后的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64447085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com