【问题标题】:Python Code to find the letter start with a in a sentencePython代码在句子中查找以a开头的字母
【发布时间】:2020-05-10 01:45:54
【问题描述】:

这里是查找句子中以 a 开头的单词的代码:“这是一棵苹果树。”

st = 'This is an apple tree'

for word in st.split():
    if word[0]=='a':
        print(word)

我想让它发挥作用,并接受我想要的任何句子,如何做到这一点? 这是我想出的代码,但没有做我想做的事。

def find_words(text):
    for word in find_words.split():
        if word[0]=='a':
            print(word)
    return find_words

find_words('This is an apple tree')

谢谢。

【问题讨论】:

    标签: python string function for-loop


    【解决方案1】:

    您可以使用以下代码。它将提供单词以“a”开头的单词列表。

    这是带有 if 子句的简单列表推导。不带参数的拆分默认按空格拆分句子,startswith方法有助于过滤'a'。

    sentence = 'This is an apple tree'
    words = [word for word in sentence.split() if word.startswith('a')]
    

    【讨论】:

    • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案添加解释并说明适用的限制和假设。
    【解决方案2】:

    问题在于您如何定义 for 循环。应该是:

    for word in text.split(' '):
         ...
    

    仅仅因为文本是你定义的函数中的参数

    【讨论】:

    • 非常感谢。它有效,但为什么它还显示警告: ?
    • 这不是警告。你是在运行 find_words('this is an apple tree') 还是只是 find_words()?
    【解决方案3】:

    如果你想打印结果试试这个:

    st = 'This is an apple tree'
    
    def find_words(text):
        for word in text.split():
            if word.startswith('a'):
                print(word)
    
    find_words(st)
    

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多