簡體   English   中英

如何在 Python 字符串中提取# 符號后的單詞

[英]How can I extract a word after # symbol in Python String

給定一個句子,例如“Im SHORTING #RSR here”,我需要提取“#”符號后面的單詞(從“#”到下一個空格,但不包括“#”)。

顯然,“#”符號可以出現在字符串的任何地方。

謝謝。

你可以使用:

sentence = "Im SHORTING #RSR here"
words = [word.lstrip('#') for word in sentence.split() if word.startswith('#')]

結果將包含句子中所有帶標簽的詞。 如果總是只有一個,只需使用words[0]

嘗試這個:

phrase = 'Im SHORTING #RSR here'

# split the input on spaces
words = phrase.split(' ')

# init empty list
comments = []

# iterate through each word
for word in words:
    # check if the first letter of the word is '#'
    if word[0] == '#':
        # add the comment to the list of comments
        comments.append(word)

# let's see what we have!
print(comments)

暫無
暫無

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

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