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

标签 python python-3.x

我正在上 Python 类(class),现在我正在努力完成其中一项任务。

目的是请求输入,通过该字符串进行整合并仅打印以字母 > 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"
print('\n'.join([word.upper() 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.

关于Python:遍历字符串并仅打印特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49367942/

相关文章:

python-3.x - 如何在 Python 3.3 上安装 Fipy

python - Scipy 优化 Curve_fit 边界错误

python - 更新 HDF 文件中的一个字段

python - 如何在 Python 中打印没有子字符串的文本

python 上下文管理器打开文件

python - 类型错误 : Can't convert 'bytes' object to str implicitly while working with sockets

python - 如何使用类方法而不是调用构造函数来初始化父类?

python - 保存时添加 ManyToMany 字段

python - 如何在电子邮件中查找集群

python-3.x - 如何从 h3 Selenium/Python 获取 href?