python - 字符串必须包含两个字符,而不仅仅是其中的 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")
启发我哦,聪明的人!:'(
解决方案
您可以使用两个计数变量来完成这项工作
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")
推荐阅读
- json - Camel DataFormat Jackson 使用蓝图 XML DSL 引发上下文异常
- jquery - 每隔一周将 JQuery datepicker 限制为 1(每两周一次)
- java - 生成带有 minifyEnabled 设置为 true 的签名 APK 后,firebase UI 输出空白
- python - 使用 Keras 进行图像分类:“预期activation_1 具有形状 (2,) 但得到的数组具有 (1,)”
- mockito - PowerMockito 链接对于 Spied 类不能可靠地工作
- python - 在python中使用整数元组作为键不起作用
- xcode - 您可以/应该在 Xcode 的 xcassets 中存储多少图像?
- unity3d - 我受到伤害但我看不到动画
- python - ValueError: Traceback(最近一次调用最后一次)
在 () - c++ - 如何动态跟踪OpenGL中的纹理单元?