将utf8字符转换为scandic字母

2024-09-20 22:53:53 发布

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

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

同样的情况也适用于更暴力的方法:

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

同样,这根本不会改变字符串。我可以从哪里找到解决方案的技巧或材料


Tags: 字符串testapi编码string格式字母slack
2条回答

我无法重现您从传入的webhook代码片段中读取soup消息的;因此,我的答案基于硬编码数据,并详细说明了Python specific text encodings ^{} and ^{}的工作原理:

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()    åä___åä

根据最初的问题和评论中的讨论,我怀疑您只是没有保存转换的结果。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

相关问题 更多 >

    热门问题