简体   繁体   English

Python:逆序打印输入(条件:只有字(至少4个字))

[英]Python: print input in reverse order (conditions: only words (at least 4 words))

I need to print input from the user in reverse order using a function.我需要使用 function 以相反的顺序打印来自用户的输入。 As a condition, just words (no floats/ int) should be allowed & at least four words need to be entered.作为一个条件,应该只允许单词(没有浮点数/整数)并且至少需要输入四个单词。 eg: How can I help you --> you help I can How例如:我可以怎样帮助你 --> 你可以帮助我怎样

It should'nt be possible to input: "4 5 6 7" or "There are 2 dogs" Here's my current code, however I didn't integrate that only strings are allowed so far:不应该输入:“4 5 6 7”或“有 2 条狗”这是我当前的代码,但是我没有集成到目前为止只允许使用字符串:

def phrase():
    while True:
        user_input = input("Please insert a phrase: ")
        words = user_input.split(" ")
        n = len(words)
        if n >= 4:
            words = words[-1::-1]
            phrase_reverse = " ".join(words)
            print(phrase_reverse)
        else:
            print("Please only insert words and at least 4 ")
            continue
        break


phrase()

I tried with if n<4 and words == str: , if n<4 and words != string etc.. However, that didn't work.我尝试了if n<4 and words == str:if n<4 and words != string等。但是,这不起作用。 Could you please help me solving this issue?你能帮我解决这个问题吗? Maybe my code is wrong in general.也许我的代码通常是错误的。

Reduce the problem to it's essential elements.将问题简化为基本要素。 The following should work - but your question looks suspiciously like homework.以下应该有效 - 但您的问题看起来像家庭作业。

    text = "test this for an example"  # use a text phrase to test.
    words = user_input.split().        # space is default for split.
    print(" ".join(reversed(words)))   # reverse list, and print as string.

result:结果:

example an for this test

If you need to filter numerics..如果您需要过滤数字..

    text = "test this for an 600 example" # use a text phrase to test.
    words = text.split()           # space is default for split.
    print(" ".join(reversed([wd for wd in words if not wd.isnumeric()])))
# filter, reverse, and print as string.

result:结果:

example an for this test

If you need to reject numerics / responses with less than 4 words in a function.如果您需要拒绝 function 中少于 4 个字的数字/响应。

def homework(text: str) -> bool:
    words = text.split()
    composed = list(reversed([wd for wd in words if not wd.isnumeric()]))
    result = len(words) == len(composed) and len(words) > 3
    if result:
        print(' '.join(composed))
    return result

It is a little bit nasty , but might be useful for you to check for nums: :)这有点讨厌,但可能对您检查 nums 有用::)

inp = input()

try:
    int(inp)
except ValueError:
    # do your operations here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM