Python:倒序打印输入(条件:只有单词(至少4个单词))
Python: print input in reverse order (conditions: only words (at least 4 words))
我需要使用函数以相反的顺序打印用户的输入。作为条件,只允许输入单词(无浮点数/整型),并且至少需要输入 四个 个单词。
例如。:
我怎么帮你
--> 你帮我如何
应该无法输入:“4 5 6 7”或“There are 2 dogs”
这是我当前的代码,但是我没有集成到目前为止只允许使用字符串:
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()
我尝试使用 if n<4 and words == str:
、if n<4 and words != string
等。但是,那没有用。你能帮我解决这个问题吗?也许我的代码一般都是错误的。
将问题简化为基本要素。
以下内容应该可行 - 但您的问题看起来很像家庭作业。
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.
结果:
example an for this test
如果您需要过滤数字..
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.
结果:
example an for this test
如果您需要拒绝函数中少于 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
有点讨厌,但可能对您检查 nums 有用! :)
inp = input()
try:
int(inp)
except ValueError:
# do your operations here
我需要使用函数以相反的顺序打印用户的输入。作为条件,只允许输入单词(无浮点数/整型),并且至少需要输入 四个 个单词。 例如。: 我怎么帮你 --> 你帮我如何
应该无法输入:“4 5 6 7”或“There are 2 dogs” 这是我当前的代码,但是我没有集成到目前为止只允许使用字符串:
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()
我尝试使用 if n<4 and words == str:
、if n<4 and words != string
等。但是,那没有用。你能帮我解决这个问题吗?也许我的代码一般都是错误的。
将问题简化为基本要素。 以下内容应该可行 - 但您的问题看起来很像家庭作业。
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.
结果:
example an for this test
如果您需要过滤数字..
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.
结果:
example an for this test
如果您需要拒绝函数中少于 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
有点讨厌,但可能对您检查 nums 有用! :)
inp = input()
try:
int(inp)
except ValueError:
# do your operations here