我试着用字母替换倒字母的字符。这就是我得到的:
alphabet = ['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']
rev_alphabet = alphabet[::-1]
sample = "wrw blf hvv ozhg mrtsg'h vkrhlwv?"
def f(alph, rev_alph):
return (alph, rev_alph)
char_list_of_tups = list(map(f, alphabet, rev_alphabet))
for alph, rev_alph in char_list_of_tups:
sample = sample.replace(rev_alph, alph)
print(sample)预期输出:你看了昨晚的节目吗?
实际输出: wrw,的vprsowv?
我知道我正在打印整个迭代的最后一个“替换”。我怎样才能避免这种情况而不把它附加到列表中,然后在单词的间距上遇到问题呢?
发布于 2022-06-17 13:59:43
这里的问题是在执行每个替换时丢失数据;简单的例子是,考虑"az"的输入。在第一个替换传递中,您将'z'替换为'a',现在有了"aa"。当您将'a'替换为'z'时,它就变成了"zz",因为您无法区分已经替换的字符和仍未更改的字符之间的区别。
对于单个字符替换,您希望使用the str.translate method (以及不严格要求的但有用的助手函数str.maketrans)在一次传递中逐个字符地对字符串进行音译。
from string import ascii_lowercase # No need to define the alphabet; Python provides it
# You can use the original str form, no list needed
# Do this once up front, and reuse it for as many translate calls as you like
trans_map = str.maketrans(ascii_lowercase[::-1], ascii_lowercase)
sample = sample.translate(trans_map)发布于 2022-06-17 14:01:20
alphabet = ['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']
# or
alphabet = [chr(97 + i) for i in range(0,26)]
sample = "wrw blf hvv ozhg mrtsg'h vkrhlwv?"
res = []
for ch in sample:
if ch in alphabet:
res.append(alphabet[-1 - alphabet.index(ch)])
else:
res.append(ch)
print("".join(res))发布于 2022-06-17 14:17:18
另一种方法是,如果您可以创建一个新的字符串代替。
alphabet = ['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']
dictRev = dict(zip(alphabet, alphabet[::-1]))
sample = "wrw blf hvv ozhg mrtsg'h vkrhlwv?"
s1="".join([dictRev.get(char, char) for char in sample])
print(s1)“你看了昨晚的节目吗?”
https://stackoverflow.com/questions/72660511
复制相似问题