I want to replace each character of a string by a different one, shifted over in the alphabet. I'm shifting by 2 in the example below, so a -> c, b -> d, etc.
I'm trying to use a regular expression and the sub function to accomplish this, but I'm getting an error.
This is the code that I have:
p = re.compile(r'(\w)')
test = p.sub(chr(ord('\\1') + 2), text)
print test
where the variable text is an input string.
And I'm getting this error:
TypeError: ord() expected a character, but string of length 2 found
I think the problem is that I the ord function is being called on the literal string "\1" and not on the \w character matched by the regular expression. What is the right way to do this?
[c for c in string]. I've provided a solution anyway (which doesn't use regexes).\wmeans[A-Za-z0-9_]in most regex parsers.[c for c in string]was my first idea, but I didn't know how to pattern match so that only values in [A-Za-z0-9] would be shifted. I also didn't realize that\wincluded'_'Thanks for your help.