![](/img/trans.png)
[英]How do I make this caesar cipher work with capital letters using an IF statement in the FOR loop?
[英]How do I count the number of capital letters using a while loop
s = input()
i = 0
while i < len(s) and (s[i]) < "A" or "Z" < s([i]):
print(i)
我一直弄错了,我不知道该怎么办。 我不想使用 for 循环只是一个 while 循环。 谢谢
您可以通过多种方式做到这一点。
如果我是你,我会使用isupper()
和sum()
生成器,
s = input("Type something...")
print(sum(1 for c in s if c.isupper()))
按照您的要求使用while ,
s = input("Type something...")
i = 0
capital = 0
while i < len(s):
if s[i].isupper():
capital+=1
i = i + 1
print(capital)
您正在将while
用于限制和计数,这将不起作用。
您必须使用while
进行限制,使用if
进行计数:
s = input()
i = 0
count = 0
while i < len(s):
print(i)
if "A" <= s[i] <= "Z":
count += 1
i = i + 1
print(f'Capitals in "{s}" = {count}')
但是,这段代码非常复杂,更好的是@AlwaysSunny 的答案或@Samwise 的评论
您的while
循环当前是这样编写的,它将在第一个小写字母处终止。 您需要在整个字符串上循环到 go,但要保持大写字母的数量。
s = input()
i = 0
c = 0
while i < len(s):
if "A" <= s[i] <= "Z":
c = c + 1 # c only goes up on capital letters
i = i + 1 # i goes up on every letter
print(i, c)
print(f"Capital letters: {c}")
一种更简单的方法是将sum
function 与isupper
一起使用:
s = input()
print(f"Capital letters: {sum(c.isupper() for c in s)}")
def Capital(In):
return sum([l.isupper() for l in In])
print(Capital(input()))
尝试使用这个:
text = input()
count=0
for letter in text:
if letter == letter.upper():
count+=1
print(letter, end=" ")
print(count-1)
我希望我已经解释清楚了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.