python - Python 中 len 函数如何替换文本

标签 python python-2.7 replace

函数 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/

相关文章:

python - 如何仅绘制日期时间数组的第一个毫秒数字

Python 列表理解一个声明和 2 个理解

python - 在 Python 中查找数组中某个值出现的索引值

python - Bottle :全局变量 'request' 未定义

python - 从分割的路径字符串构建新的路径字符串

python-2.7 - 如何使用 python ctypes 访问另一个进程的 PEB

javascript - 界面网页 View 。使用 javascript 替换 css 属性

excel - 按列标题搜索和替换

php - 在 PHP 中删除从第一个字符出现到字符串末尾的所有内容

Python OpenCV 填写红色圈出的圆圈