【问题标题】:Strings containing specific characters [duplicate]包含特定字符的字符串 [重复]
【发布时间】:2018-03-11 11:52:11
【问题描述】:

使用这段代码,我想要做的是不让输入不包含元音的名称。它在 if 只有 1 个元音时有效,但当我尝试多个元音时它不会。我知道python中的表示和/或。我进行了研究,但我没有找到为什么会发生这种情况的解释。代码的 sintaxis 没问题。谁能告诉我这个角色的工作原理?

var = False #Sets var to False

while var == False: #While var is False do this:

  name = str(input("What is your name? ")) #Input name and Print what is your name?

  if "a" or "e" or "i" or "o" or "u" in name: #If name contains a or e or i or o or u
    var = True #Set var to True

print ("Success") #Print Success

【问题讨论】:

  • 虽然副本使用 == 作为示例 - 如果根据您的问题使用 in 也是一样的。

标签: python string python-3.x character


【解决方案1】:
var = False     
while var == False:     
  name = str(input("What is your name? ")) 
  if any(i in 'aeiou' for i in name.lower()):   
    var = True  

print ("Success")

【讨论】:

  • “aeiouAEIOU”和name.lower()哪个更有效?
  • 仅对于小名字,name.lower() 更快
  • 谢谢,因为我想要尽可能少的编译时间!
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多