我正在寻找一个脚本代码,以搜索字符串的前3个单词。
例如:
例如:
words = 'I am confused looking for 3 words from the front'
预期结果:
'I am confused'
words = 'I am confused looking for 3 words from the front'
预期结果:
'I am confused'
split()
方法将字符串拆分为列表。然后,你可以使用列表切片([:3]
)从句子中提取前三个单词。最后,你需要使用 .join()
将结果合并为一个新字符串:words = 'I am confused looking for 3 words from the front'
' '.join(words.split()[:3])
>> 'I am confused'