要从给定的多行字符串中计算单词“the”出现的次数,而不使用内置函数,可以通过遍历字符串中的每个字符来实现。以下是一个示例代码:
def count_the(text):
count = 0
word = ""
for char in text:
if char.isalpha():
word += char.lower()
else:
if word == "the":
count += 1
word = ""
if word == "the":
count += 1
return count
# 示例多行字符串
text = """
The quick brown fox jumps over the lazy dog.
The dog barked at the fox, but the fox kept running.
"""
print(count_the(text)) # 输出: 3
isalpha()
判断字符是否为字母。lower()
将字符转换为小写,以确保不区分大小写。word
是否为 "the",以处理字符串末尾的单词。通过这种方式,可以有效地计算出多行字符串中单词“the”的出现次数,同时避免了使用内置函数。
领取专属 10元无门槛券
手把手带您无忧上云