函数 replaced = line[:pos] + replacement + line[pos+len(marker):]
中的代码 len(marker)
如何删除该值输出中字符串 marker
的值,用于查找字符串的长度。
帮助我理解。
#Example 1
marker = "AFK"
replacement = "away from keyboard"
line = "I will now go to sleep and be AFK until lunch time tomorrow."
pos = line.find(marker)
replaced = line[:pos] + replacement + line[len(marker)+pos:]
print replaced
输出
I will now go to sleep and be away from keyboard until lunch time tomorrow.
最佳答案
我们想要在文本行
中找到“AFK”的索引。这是通过
pos = line.find(marker)
我们看到答案是30
。因此,我们将从 line
中获取从开头到索引 30 的文本。这是I will now go to sleep and be
。然后我们将远离键盘
附加文本,然后我们将在行
中附加文本的其余部分。
因此,我们将采用 len(marker)
,即 3
,然后将其添加到我们获得的 pos
值中。结果是 33
。然后,我们将从索引 33
一直到该句子的末尾 line[len(marker)+pos:]
。
我们一起得到
replaced = line[:pos] + replacement + line[len(marker)+pos:]
I will now go to sleep and be away from keyboard until lunch time tomorrow.
关于python - Python 中 len 函数如何替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49401065/