[英]Compare a Python substring to a char value
I'm trying to iterate through a loop in Python and compare the current char on a string, with a constant char.我正在尝试遍历 Python 中的一个循环,并将字符串中的当前字符与常量字符进行比较。
for i in s:
if(s[i]=='I')
mySum++
This code gives me a syntax error on the if statement.此代码在 if 语句中给我一个语法错误。
The same code in Java would look something like this Java 中的相同代码看起来像这样
for(int i = 0; i<s.length();i++)
{
if(s.charAt(i)=='I')
{
mySum++
}
}
How do I do this in Python?我如何在 Python 中执行此操作?
Use += 1
in python:在 python 中使用
+= 1
:
for i in s:
if i == 'I':
mySum += 1
Also add a colon after if
.还要在
if
之后添加一个冒号。
Just like @U12-Forward suggested, there is no ++
operator in python. So you'll have you use the +=
operator.就像@U12-Forward 建议的那样,python 中没有
++
运算符。因此您将使用+=
运算符。
However, I prefer @Iain answer rather.但是,我更喜欢@Iain 的回答。
my_sum = s.count('I')
Problem is not in if(s[i]=='I')
, the problem is in: mySum++
.问题不在
if(s[i]=='I')
,问题在: mySum++
。
Python do not support ++
operator. Python 不支持
++
运算符。 You can do it by following ways:您可以通过以下方式进行:
mySum++ --> mySum +=1
## Or
mySum++ --> mySum = mySum + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.