函数len如何替换Python中的文本

2024-03-29 12:46:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输出

^{pr2}$

Tags: 函数字符串代码fromposlenexampleline
1条回答
网友
1楼 · 发布于 2024-03-29 12:46:11

我们要在文本line中找到“AFK”的索引。这就结束了

pos = line.find(marker)

我们看到答案是30。所以我们将把line中的文本从开始到索引30。这是I will now go to sleep and be。然后我们将追加文本away from keyboard,然后将其余文本追加到line。在

所以我们将取len(marker),它是{},然后我们将把它加到我们得到的pos的值中。结果是33。然后,我们将从索引33一直到句子的结尾,line[len(marker)+pos:]。在

我们在一起

^{pr2}$

I will now go to sleep and be away from keyboard until lunch time tomorrow.

相关问题 更多 >