如何替换字符串中的字符串

2024-04-27 19:16:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本字符串。我需要解码文本字符串,即用对应的字符替换字符串中的每个字符,然后读取消息。我怎样才能做到这一点?

例如:

g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.

是编码的。我需要用c替换a,用d替换b,等等。在Python中如何做到这一点?

当我更换时有问题。当我做replace all时,我会替换被替换的字符,这不是我想要的。我想一次替换一个字符并解码消息。


Tags: 字符串文本消息解码字符grwmszw
3条回答

显然string.maketrans()是这样做的

>>> s = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
>>> from string import maketrans, ascii_lowercase
>>> T = maketrans(ascii_lowercase, ascii_lowercase[2:] + ascii_lowercase[:2])
>>> s.translate(T)
"i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url."

使用Python3,它也可以像这样。

import string

message = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq   ypc " \
          "dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq " \
          "rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu " \
          "ynnjw ml rfc spj."

table = str.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:] + string.ascii_lowercase[:2])

print(message.translate(table))

使用str.maketrans(x[,y[,z]])映射字母“x中的每个字符都将映射到y中相同位置的字符。” 解释来自here

对于子字符串a-z string.ascii_小写[2:]lookhere

我找到了一种不用maketrans()的方法。我不想依赖这样的功能,所以我自己做了。我花了几个小时才弄明白:

def shiftAll(text, shift):
    '''
    @param text - string of text to be shifted
    @param shift - the number of times to shift all letters; int value only

    In range 'a' to 'z' and 'A' to 'Z'
    Initializes empty string newText and appends the new shifted letters to it

    To shift right on th alphabet ex: a -> b or n -> y,
    enter a positive shift ex: 1, 2, 4
    To shift left on the alphabet ex: b -> a or q -> m,
    enter a negative shift ex: -2, -1, -5

    Handles:
    Error where index out of range
    Sum of shift and position is greater than 25 or less than 0
        ~Allows cases where the letter may be 'a'(j (position) == 0)
        but the shift is negative
        ~Allows cases where the letter may be 'z'(j (position) == 25)
        but the shift is positive

    returns newText
    '''
    alpha = "abcdefghijklmnopqrstuvwxyz"

    newText = ""
    for i in text:
        if ((i not in alpha) and (i not in alpha.upper())):
            newText += i        #only replaces alphabetical characters  

        for j in range(len(alpha)):     #26 letters, so positions 0-25
            if ((i == alpha[j]) or (i == alpha[j].upper())):
                while (j + shift > 25):    #to avoid index out of range error
                    shift -= 26
                while (j + shift < 0):   #to avoid index out of range error
                    shift += 26

                if(i == alpha[j].upper()): #because letters can be capital too
                    newText += alpha[j + shift].upper()
                else:
                    newText += alpha[j + shift]

    return newText

string = input("Enter anything with letters in it: ")
aShift = int(input("Enter how many places you want to shift the letters: ") 
#let's pretend the user will actually enter an int value in aShift
result = shiftAll(string, aShift)
print(result)

这对任何字符串都有效,并按班次移动字符串中的所有字母。班次必须是整数

相关问题 更多 >