将 utf-8 字符转换为扫描字母

问题描述

我正在努力尝试编码一个字符串,其中 scandic 字母为 utf-8 格式。 例如,我想转换以下 细绳: test_string = "\xc3\xa4\xc3\xa4abc" 进入形式: test_string = "ääabc" 最终目标是通过 API 将此字符串发送到 Slack-channel。我做了一些测试,发现 Slack 可以正确处理扫描字母。 我尝试了以下命令: test_string= test_string.encode('latin1').decode('utf-8') 但这根本不会改变字符串。

同样适用于更暴力的方法

def simple_scand_convert(string):
   string = string.replace("\xc3\xa4","ä")

同样,这根本不会改变字符串。我可以从哪里寻找解决方案的任何提示或材料?

解决方法

根据原始问题和评论中的讨论,我怀疑您只是没有保存转换结果。 Python 字符串是不可变的,因此仅对传递给函数的字符串进行更改不会对原始字符串执行任何操作:

In [42]: def change_string(s):
    ...:     s = "hello world"
    ...:
    ...: test_s = "still here"
    ...: change_string(test_s)
    ...: print(test_s)
still here

相反,您需要在函数中返回转换结果并重新分配变量:

In [43]: def change_string(s):
    ...:     s = s.encode('latin1').decode('u8')
    ...:     return s
    ...:
    ...: test_s = "\xc3\xa4\xc3\xa4abc"
    ...: test_s = change_string(test_s)
    ...: print(test_s)
ääabc
,

我无法重现您从传入的 webhook 中读取汤消息 代码片段;因此,我的回答基于硬编码数据,并详细展示了 Python specific text encodings raw_unicode_escape and unicode_escape 如何工作:

test_string = "\\xc3\\xa5\\xc3\\xa4___\xc3\xa5\xc3\xa4"    # hard-coded
print('test_string                  ',test_string)
print('.encode("raw_unicode_escape")',test_string.encode( 'raw_unicode_escape'))
print('.decode(    "unicode_escape")',test_string.encode( 'raw_unicode_escape').decode( 'unicode_escape'))
print('.encode("latin1").decode()   ',test_string.encode( 'raw_unicode_escape').decode( 'unicode_escape').
              encode( 'latin1').decode( 'utf-8'))

输出:\SO\68069394.py

test_string                   \xc3\xa5\xc3\xa4___åä
.encode("raw_unicode_escape") b'\\xc3\\xa5\\xc3\\xa4___\xc3\xa5\xc3\xa4'
.decode(    "unicode_escape") åä___åä
.encode("latin1").decode()    åä___åä