解码函数在for语句中不工作

2024-04-19 11:05:19 发布

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

我试图用符号(UTF-8格式)替换用户输入中的某些特定字符。解码似乎正在工作,但仅适用于打印时的b字符。字符a保持不变

此外,当我从字符字典中删除charb时,chara将替换为指定的字符,打印时不会出现任何问题

characters = {
    'a': b'\xe1\x94\x91',
    'b': b'\xca\x96'
}

string = str()
    
for i, j in characters.items():
    string = arg.replace(i, j.decode('utf-8')) # arg is the input

print(string)

我认为问题发生在for循环中,任何帮助都将不胜感激


Tags: 用户forstring字典格式arg符号解码
2条回答

字符串在Python中是不可变的

也就是说,字符串的值在初始化一次后永远不能更改

因此,在执行字符串替换时,必须使用

my_string = my_string.replace

以下是工作示例:

# File name: decode-demo.py

characters = {
    'a': b'\xe1\x94\x91',
    'b': b'\xca\x96'
}


arg = input("Enter a string: ")

output = arg
    
for i, j in characters.items():
    output = output.replace(i, j.decode('utf-8'))

print(output)

输出:

> python decode-demo.py

Enter a string: abba

ᔑʖʖᔑ

在循环的每次迭代中,您都要替换输入字符串中的出现:argstring中以前的所有替换将被丢弃。您必须重用上一次迭代中的字符串,以便替换内容累积:

string = arg
    
for i, j in characters.items():
    string = string.replace(i, j.decode('utf-8')) # arg is the input

相关问题 更多 >