简体   繁体   中英

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.

for i in s:
        if(s[i]=='I')
            mySum++
            

This code gives me a syntax error on the if statement.

The same code in Java would look something like this

for(int i = 0; i<s.length();i++)
{
     if(s.charAt(i)=='I')
         {
          mySum++
         }
}

How do I do this in Python?

Use += 1 in python:

for i in s:
    if i == 'I':
        mySum += 1

Also add a colon after if .

Just like @U12-Forward suggested, there is no ++ operator in python. So you'll have you use the += operator.

However, I prefer @Iain answer rather.

my_sum = s.count('I')

Problem is not in if(s[i]=='I') , the problem is in: mySum++ .

Python do not support ++ operator. You can do it by following ways:

mySum++ --> mySum +=1

## Or

mySum++ --> mySum = mySum + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM