简体   繁体   中英

How do I unstring in python

因此,我正在尝试制作一个文本加密程序,该程序会将文本中的字母更改为不同的顺序字母,但是a = key [1](键是重新排列的字母的名称),但是由于key [1 ]不能分配给乱扔垃圾,有关如何解决此问题的任何想法。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM