python - Python - .insert() 方法只替换单词的第一个字母?
问题描述
我之前已经发布过这个问题,并且我已经能够将程序缩减为一个用于测试目的的函数。我没有收到任何错误,但我遇到了一个让我陷入困境的错误。我可以替换快捷方式,但它只替换快捷方式的第一个字母。
这是代码:
from tkinter import *
root = Tk()
text = Text(root)
text.pack(expand=1, fill=BOTH)
syntax = "shortcut = sc" # This will be turned into a function to return the shortcut
# and the word, I'm only doing this for debugging purposes.
def replace_shortcut(event=None):
tokens = syntax.split()
word = tokens[:1]
shortcut = tokens[2:3]
index = '1.0'
while 1:
index = text.search(shortcut, index, stopindex="end")
if not index: break
last_idx = '%s + %dc' % (index, len(shortcut))
text.delete(index, last_idx)
text.insert(index, word)
last_idx = '%s + %dc' % (index, len(word))
text.bind('<space>', replace_shortcut)
text.mainloop()
给定的快捷方式,在我们的例子中,'sc' 将在输入空格后变成 'shortcutc'。任何帮助表示赞赏!
解决方案
你有两个问题。
您将变量shortcut
定义为['sc']
而不是'sc'
. 所以len(shortcut)
总是 1(数组的长度)而不是 2(字符串的长度)。你最终只会删除一个字符。可能你想要len(shortcut[0])
[你也有同样的问题len(word)
。您将始终得到 1,即数组的长度。]
此外,您的 while 循环的最后一行应该设置index
而不是last_idx
,因为这是将在下一次搜索中使用的变量。
推荐阅读
- python - KubernetesPodOperator - 运行从 XCOM 提取的整个命令
- openmodelica - CodegenCFunctions.tpl -> algStmtAssignWithRhsExpStr:未处理的 lhs 表达式错误
- python - 验证 int(input()) python
- c# - PartialView 中的@Html.ActionLink 找不到我的控制器操作
- laravel - 碳:比较日期实例给出了意想不到的结果
- amazon-web-services - 如何使用假定角色为其他帐户执行 terraform 配置?
- flutter - 动态创建和删除文本字段颤动
- testing - 运行登录操作占jmeter中总请求的1/50或1/100比例
- asp.net - Xml 变量替换不适用于 web.config 中的单个部分键
- arrays - 如何将文本文件放入数组。使用 awk,每个元素在空行上分开