The C code is modifying password
in-place. So, the closest equivalent would be:
def myencrypt(password, mkey):
for i in range(len(password)):
password[i] = chr(ord(password[i]) - mkey)
That assumes password
is a list
of characters, rather than a string.
Also, notice that I'm calling chr
on the result of each ord(password[i]) - mkey
, because otherwise you're replacing each character with a number—for example, myencrypt(['a'], 32)
would give you [65]
instead of ['A']
. (This isn't necessary in C, because 65
and 'A'
are the same value in C.)
You're more likely going to want to call this function with a string, and get back a string. You can still use the C-style in-place functionality to do it, just by converting and converting back:
def myencrypt(password, mkey):
newpass = list(password)
for i in range(len(newpass)):
newpass[i] = chr(ord(newpass[i]) - mkey)
return ''.join(newpass)
However, this isn't a very Pythonic way to do things. A more idiomatic solution would be:
def myencrypt(password, mkey):
return ''.join(chr(ord(ch) - mkey) for ch in password)
And that brings up a more general point: Except in very trivial cases, trying to "convert C code to Python" directly is a bad idea. Instead, figure out what the C code does, and write new Python code that accomplishes the same task in the best way for Python, rather than in the way the C code did it.