首页 > 解决方案 > 字符串必须包含两个字符,而不仅仅是其中的 1 个

问题描述

对你们来说可能听起来太简单了,所以我很抱歉浪费了你们的时间,但这打破了我可怜的大脑。所以对于它的价值,这里是:

第一个任务没问题:如果字符串有“i”或“u”,打印“there is an i or a u”。

string = "demo loops for you"
for char in string:
   if char == 'i' or char == 'u':
       print("There is an i or a u")

第二个是令人心碎的,尤其是在第一个条件下:

如果字符串同时具有“i”和“u”,则打印“同时存在 i 和 u”,因此如果只有“i”但没有“u”,则打印“只有 i”,如果只有"u" BUT NO "i",然后打印"there is only u"

第一个条件的这个块不起作用。它仍然打印(即使只有一个字符->“i”):

string = "i can demo loops"
for char in string:
   if char == 'i' and 'u':
       print("There is both an i or u")

启发我哦,聪明的人!:'(

标签: pythonstringbooleanoperators

解决方案


您可以使用两个计数变量来完成这项工作

string = "demo loops  u for yo"

icount=string.count('i')
ucount=string.count('u')


if (icount >0 and ucount==0) :
  print ("there is only i but not u")

if (icount ==0 and ucount>0):
  print ("there is only u but not i")

if (icount >0 and ucount>0):
  print ("there are both u and i")

推荐阅读