简体   繁体   English

在循环中使用if标记检查user_input

[英]check user_input with if token in a loop

I am trying to write a function that checks my input to see whether I have entered the character '?'. 我正在尝试编写一个检查输入的函数,看看我是否输入了字符'?'。

This is what I got so far: 这是我到目前为止所得到的:

def check_word():
   word = []
   check = 0
   user_input = input('Please enter a word that does not contain ?: ')

   for token in user_input.split():
      if token == '?':
        print('Error')
check_word()

My input: hello? 我的意见:你好?
It is supposed to show 'Error'. 它应该显示'错误'。 But it doesn't show anything. 但它没有显示任何东西。 Could you please tell me what wrong it is in my code. 你能告诉我我的代码有什么不对吗?

I would use the in operator to do this 我会使用in运算符来执行此操作

def check_word(s):
    if '?' in s:
        print('Error')

For example 例如

>>> check_word('foobar')
>>> check_word('foo?')
Error

The problem is how you split the string of the user_input . 问题是如何拆分user_input的字符串。

user_input.split():

The example doesn't contain whitespaces so the condition isn't met. 该示例不包含空格,因此不满足条件。 If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces. 例如,如果要检查带空格的句子,则应将其拆分为: user_input.split(' ')将其拆分为空格。

But for this example you have two choices: 但是对于这个例子,你有两个选择:

1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ? 1)你可以迭代输入本身,因为你想检查字符串中的每个字符是否是一个? .

That is, change user_input.split(): into simply user_input without splitting. 也就是说,将user_input.split():简单地改为user_input而不进行拆分。 This option is good if you might ever want to add some sort of action for each char. 如果您可能希望为每个char添加某种操作,则此选项很有用。

2) It's very easy just to use in , like this: 2)这是非常简单,你只使用in ,就像这样:

if '?' in s:
    print('There is a question mark in the string')

This is a very simple solution that you can expand and check for other chars in the string as well. 这是一个非常简单的解决方案,您可以扩展并检查字符串中的其他字符。

It's because user_input.split() splits the user_input by whitespace. 这是因为user_input.split()按空格分割user_input Since hello? hello? does not contain any whitespaces, token is equal to your input and the loop is executed once. 不包含任何空格, token等于您的输入,循环执行一次。

You should iterate over user_input instead, or simply check if '?' in user_input 您应该迭代user_input ,或者只是检查if '?' in user_input if '?' in user_input . if '?' in user_input

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

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