Python:遍历字符串并只打印特定的单词

Python:遍历字符串并只打印特定的单词,python,python-3.x,Python,Python 3.x,我正在学习python,现在我正在努力完成其中一项任务 其目的是请求输入,通过该字符串进行集成,并仅打印以字母>g开头的单词。如果单词以大于g的字母开头,我们将打印该单词。否则,我们将清空该单词并遍历字符串中的下一个单词以执行相同的检查 这是我的代码和输出。如果您能提供一些解决问题的建议,我将不胜感激 # [] create words after "G" following the Assignment requirements use of functions, menhod

我正在学习python,现在我正在努力完成其中一项任务

其目的是请求输入,通过该字符串进行集成,并仅打印以字母>g开头的单词。如果单词以大于g的字母开头,我们将打印该单词。否则,我们将清空该单词并遍历字符串中的下一个单词以执行相同的检查

这是我的代码和输出。如果您能提供一些解决问题的建议,我将不胜感激

        # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds
        # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)
        # [] copy and paste in edX assignment page

        quote = input("Enter a sentence: ")
        word = ""

        # iterate through each character in quote
        for char in quote:

            # test if character is alpha
            if char.isalpha():
                word += char 

            else:


                if word[0].lower() >= "h":
                    print(word.upper())   

                else:
                    word=""

    Enter a sentence: Wheresoever you go, go with all your heart
    WHERESOEVER
    WHERESOEVERYOU
    WHERESOEVERYOUGO
    WHERESOEVERYOUGO
    WHERESOEVERYOUGOGO
    WHERESOEVERYOUGOGOWITH
    WHERESOEVERYOUGOGOWITHALL
    WHERESOEVERYOUGOGOWITHALLYOUR



The output should look like,

Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART

只需使用
split
进行列表理解即可:

s = "Wheresoever you go, go with all your heart"
print(' '.join([word for word in s.split() if word[0].lower() > 'g']))
# Wheresoever you with your heart
修改以与所需输出匹配(使所有大写和新行都匹配):

列表理解:

s = "Wheresoever you go, go with all your heart"
for word in s.split():  # Split the sentence into words and iterate through each.
    if word[0].lower() > 'g':  # Check if the first character (lowercased) > g.
        print(word.upper())  # If so, print the word all capitalised.

您的问题是,您只是在
else
子句中将
word
重置为空字符串。您需要在
print(word.upper())
语句之后立即将其重置为空字符串,这样代码才能正常工作


也就是说,如果您正在学习的类没有明确禁止使用string方法,那么您应该研究string方法,特别是
string.split()

,这里是一个可读且有注释的解决方案。想法是首先使用
re.findall
(regex-package)将句子分割成一个单词列表,并在这个列表中迭代,而不是像您那样迭代每个字符。因此,只打印以大于“g”的字母开头的单词非常容易:

import re

# Prompt for an input sentence
quote = input("Enter a sentence: ")

# Split the sentence into a list of words
words = re.findall(r'\w+', quote)

# Iterate through each word
for word in words:
    # Print the word if its 1st letter is greater than 'g'
    if word[0].lower() > 'g':
        print(word.upper())
更进一步,这里还有一个基于完全相同逻辑的单线式解决方案,使用列表理解:

import re

# Prompt for an input sentence
quote = input("Enter a sentence: ")

# Print each word starting by a letter greater than 'g', in upper case
print(*[word.upper() for word in re.findall(r'\w+', quote) if word[0].lower() > 'g'], sep='\n')

首先,如果您的老师没有禁止所有显式字符串方法的使用,请从
quote.split()
开始。然后您可以迭代单词,而不是迭代字符并尝试动态重建单词。您得到的错误是什么?@smb564他说他在哪里得到错误?他显示了预期输出和实际输出,它们明显不同。您现有代码的问题是,您在使用后从未再次设置
word='
,因此您只需继续附加到同一个单词(这也意味着
word[0]
始终是
'W'
)。问题规范甚至说“清空单词”;你刚才漏掉了那部分。您应该能够找出在代码中添加它的位置。。。。尽管我认为这对于“通过字符串进行集成”而不仅仅是通过字符串进行迭代是一个很好的含义。这基本上是字符串的离散积分。:)这与所需的输出不匹配。而且,由于在使用集合进行存储时丢弃了顺序(以及任何DUP),因此无法恢复所需的输出。我想,单词顺序以及单词大小写必须保留在老师想要的答案中。这里不是这样。还有,你有什么反对理解的?使用setcomp而不是map可以删除
set
调用和lambda,从而使代码更短、更可读,并且可能更有效地引导。@abarnertfixed@sciroccoricsFixed他不想在字符串模块中使用函数。如果你只是想把评论复制到一个答案中,至少要把它做对。看看你想要的结果。您没有将单词大写,也没有将每个单词打印在自己的行中。任何人只要能很好地理解这段代码,并将其提交给家庭作业答案,就应该能够自己想出如何做到这一点,但你可能应该在回答中提到他需要这样做。你可能想把这个问题分解成一个完整的for循环,并将其添加到OP的答案中,OP是一个苦苦挣扎的学生。@wwii你的意思是非列表理解版本吗?@Zhekakova过滤标点符号完全没有必要,因为OP没有对此做出任何规定问题的任何地方。或者,如果他想这样做,你的回答很好,他可以参考你的回答。:)
import re

# Prompt for an input sentence
quote = input("Enter a sentence: ")

# Split the sentence into a list of words
words = re.findall(r'\w+', quote)

# Iterate through each word
for word in words:
    # Print the word if its 1st letter is greater than 'g'
    if word[0].lower() > 'g':
        print(word.upper())
import re

# Prompt for an input sentence
quote = input("Enter a sentence: ")

# Print each word starting by a letter greater than 'g', in upper case
print(*[word.upper() for word in re.findall(r'\w+', quote) if word[0].lower() > 'g'], sep='\n')