使用Python打印一行特定字符串的下一个单词可以通过以下步骤完成:
split()
函数将字符串按空格分割为单词列表。sentence = "This is a sample sentence"
word_list = sentence.split()
target_word = "sample"
index = -1
for i in range(len(word_list)):
if word_list[i] == target_word:
index = i
break
if index != -1 and index < len(word_list) - 1:
next_word = word_list[index + 1]
print("Next word:", next_word)
else:
print("No next word found.")
完整的Python代码如下:
sentence = "This is a sample sentence"
word_list = sentence.split()
target_word = "sample"
index = -1
for i in range(len(word_list)):
if word_list[i] == target_word:
index = i
break
if index != -1 and index < len(word_list) - 1:
next_word = word_list[index + 1]
print("Next word:", next_word)
else:
print("No next word found.")
这段代码将给出特定字符串"sample"的下一个单词,并打印出来。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云