So I am trying to make a text encryptionish program that will change the letters in text to a different ordred alphabet, however a = key[1](Key being the name of the rearanged alphabet) but it dosn't work because key[1] can't be assigned to a litteral, any ideas of how to get arround this.
-
1If you provided some code that illustrated the problem, it would be a lot easier for us to help you. – Christian Tapia Mar 26 '14 at 02:29
2 Answers
So key
is your rearranged alphabet, and ALPHA
is the normal alphabet.
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
key = 'zwlsqpugxackmirnhfdvbjoeyt'
msg = 'secretmessage'
code = []
for i in msg:
code.append(key[ALPHA.index(i)])
print(''.join(code))
Make the string after encoding, rather than during encoding.

- 794
- 6
- 17
Strings in Python, and many other languages, are immutable, because reasons.
What you need is to create a new string, replacing characters as needed.
For byte strings (that in Python are plain byte arrays) there's .translate
. It takes a 256-byte string that describes how to replace each possible byte.
For Unicode strings .translate
takes a map which is a bit more convenient but still maybe cumbersome:
unicode('foo bar').translate({ord('f'): u'F', ord('b'): u'B'})
In general case, something like this should work:
def transform_char(char):
# shift a characte 3 positions forward
return chr(ord(char) + 3)
def transform(source_string):
return ''.join(transform_char(c) for c in source_string)
What happens in transform
? It generates a list of transformed characters ([transform_char(c) for c in source_string]
) is called a "list comprehension". This list contains a transformed character for each character in source_string
. Then all elements of this list are efficiently join
ed together by placing an empty string ''
between them.
I hope it's enough for you now.