Python:迭代字符串并仅打印特定单词

时间:2018-03-19 16:33:14

标签: python python-3.x

我正在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

4 个答案:

答案 0 :(得分:3)

只需使用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.

答案 1 :(得分:0)

s = "Wheresoever you go, go with all your heart"
out = s.translate(str.maketrans(string.punctuation, " "*len(string.punctuation)))
desired_result = [word.upper() for word in out.split() if word and word[0].lower() > 'g']
print(*desired_result, sep="\n")

答案 2 :(得分:0)

这是一个可读和评论的解决方案。这个想法首先是使用re.findall(正则表达式包)将句子分成单词列表并迭代这个列表,而不是像你那样迭代每个字符。然后很容易只打印以字母开头的单词,而不是' 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')

答案 3 :(得分:-1)

您的问题是,您只是将word重置为else子句中的空字符串。您需要在print(word.upper())语句后立即将其重置为空字符串以及代码,因为您已将其编写为正常工作。

话虽如此,如果没有明确禁止你正在上课,你应该研究字符串方法,特别是string.split()