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

问题描述 投票:0回答:5

我有一个文本字符串。我需要解码文本字符串,即将字符串中的每个字符替换为其对应的字符串,然后读取该消息。我该如何实现这一目标?

例如:

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中执行此操作?

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

python string
5个回答
6
投票

显然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."

1
投票

使用Python 3,它也可以是这样的。

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_lowercase [2:]看起来here


-1
投票

我找到了一种方法,没有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)

这适用于任何字符串,并通过移位移动字符串中的所有字母。转变必须是一个int。


-1
投票

仅使用内置的ins:转换为ASCII add 2并返回chr。

In [1]: str = "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."
In [2]: res = ''

In [3]: for char in str:
    tmp = char
    if tmp.isalpha():
        tmp = ord(tmp)+2
        if tmp == 123: 
            tmp = 97
        if tmp == 124:
            tmp = 98
        tmp = chr(tmp)
    res += tmp
    ....:     

In [4]: res
Out[4]: "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."

-1
投票

使用函数替换字符串上的字符串的简单方法是:

def esta (elemento,lista):                      ##here create a function with element 
    for i in range (len(lista)):                ## in a list, and search the [i]
        if lista[i]==elemento:
            return i
    return -1

## principal program:

abc=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a","b"]
a="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."
cad=""
cont=0
for car in a:
    if esta(car,abc)!=-1:
        cad=cad+abc[esta(car,abc)+2]
    else:
        cad=cad+car
print(cad)

如果您需要更多解释,请与我联系。

© www.soinside.com 2019 - 2024. All rights reserved.