0

I'm learning python and trying to make some code to encrypt a string using the Playfair cipher. I have made a java file that does this, but in the interest of learning python I want to recreate the code.

The cipher requires different functions to be applied to letters at even spaces than odd spaces. For example, if we encrypted 'Hello World', H l o o l would all be encrypted with the even function, and e l W r d would all be encrypted with the odd function.

I could achieve this in java by using for(int i = 0; i < string.length(); i++) and if(i % 2 == 0) -> even function and else -> odd function. But the syntax to do this in python is a bit different so I'm not sure how to do this.

I have for x in string:. I want to be able to separate characters that are at even and odd positions in 'string'.

martineau
  • 119,623
  • 25
  • 170
  • 301
Henry Hale
  • 11
  • 1

1 Answers1

1

The enumerate function wraps an iterable to produce a new iterator that gives you both index and value at each iteration:

for i, x in enumerate(string):
    if i % 2 == 0:
        # Even stuff
    else:
        # Odd stuff
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271