簡體   English   中英

從字符串中提取前 3 個單詞

[英]Extract first 3 words from string

我正在尋找一個腳本代碼來搜索字符串的前 3 個單詞。

示例:

words = 'I am confused looking for 3 words from the front'

預期結果:

'I am confused'

您可以使用 將字符串拆分為一個列表。 split()方法。 完成此操作后,您可以使用列表切片 ( [:3] ) 從句子中提取前 3 個單詞。 最后,您需要使用.join()將結果重新連接到一個新字符串中:

words = 'I am confused looking for 3 words from the front'
' '.join(words.split()[:3])
>> 'I am confused'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM