python - 如何在不使用正则表达式的情况下删除 -> 之后的字符
问题描述
给定一个字符串 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'
这仅处理每个字符串一个“->”,但您可以对其进行迭代。
推荐阅读
- swift - 如何快速裁剪图像
- python - sklearn 中的仅分类器管道
- javascript - 如何使用 gem 'jquery-validation-rails' 验证 AJAX 请求的表单
- python - 然后用输入替换列表中大于 100 的某些对象
- ios - 在 tableView 更新期间对数据源的线程安全访问
- mongodb - MongoDB:为嵌入式数组创建索引
- sql - 使一列自动,以便每次输入新记录时它可以增加一
- r - R 的控制流与多个 if 语句的行为不符
- linux-kernel - 如何在 beaglebone 自定义 linux 上自动连接 wifi
- promise - 使用 esri/request 触发的多个 XHR 请求在使用 dojo/promise/all 处理时返回延迟