简体   繁体   English

我如何在python中解串

[英]How do I unstring in python

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

So key is your rearranged alphabet, and ALPHA is the normal alphabet. 因此, key是您重新排列的字母,而ALPHA是普通字母。

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 . 由于原因 ,Python和许多其他语言中的字符串是不可变的。

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 . 对于字节字符串(在Python中是纯字节数组),存在.translate It takes a 256-byte string that describes how to replace each possible byte. 它需要一个256字节的字符串来描述如何替换每个可能的字节。

For Unicode strings .translate takes a map which is a bit more convenient but still maybe cumbersome: 对于Unicode字符串, .translate一个映射,该映射稍微方便一些,但仍然很麻烦:

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 ? transform会发生什么? It generates a list of transformed characters ( [transform_char(c) for c in source_string] ) is called a "list comprehension". 它生成一个转换后的字符列表( [transform_char(c) for c in source_string] )称为“列表理解”。 This list contains a transformed character for each character in source_string . 此列表包含source_string每个字符的转换字符。 Then all elements of this list are efficiently join ed together by placing an empty string '' between them. 然后,通过在列表中的所有元素之间放置一个空字符串'' ,可以将它们有效地join在一起。

I hope it's enough for you now. 我希望现在对您已经足够。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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