pythoncharcharat

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?


Solution

  • Use += 1 in python:

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

    Also add a colon after if.