替换字符串列表中的子字符串或解码

问题描述 投票:1回答:2

我有一个字符串列表,我将在PYTHON工作,有些字符串包含特殊字符:üäö等等。

我有2个解决方案:

  1. 通过替换字符串列表中的子字符串来处理获取的数据。
  2. 解码python中列表中获取的内容。 lista_names_d = ['L \ xc3 \ xbcneburg Bockelsberg 2','L \ xc3 \ xbcneburg Bockelsberg 1','L \ xc3 \ xbcneburg Bockelsberg 3','L \ xc3 \ xbcneburg Bockelsberg 5']

我试过this

lista_names_d = [name.replace('\xc3\xbc', 'ü') for name in lista_names_d]

这什么都不做

我试过this

your_unicode_string = "L\xc3\xbcneburg Kaltenmoor BHKW 1"
correct_unicode_string = your_unicode_string.encode('latin1').decode('utf8')

错误:UnicodeDecodeError:'ascii'编解码器无法解码位置1中的字节0xc3:序号不在范围内(128)

任何帮助都非常感谢

python sql string special-characters
2个回答
0
投票

那么使用函数unicode呢?此代码打印正确的重音:

lista_names_d = [ 'L\xc3\xbcneburg Bockelsberg 2', 'L\xc3\xbcneburg Bockelsberg 1', 'L\xc3\xbcneburg Bockelsberg 3','L\xc3\xbcneburg Bockelsberg 5' ]

for item in lista_names_d:
    print(unicode(item, 'utf-8'))

0
投票

检查encoding文档:

for city in lista_names_d:
    print city.decode('utf8')
# Lüneburg Bockelsberg 2
# Lüneburg Bockelsberg 1
# Lüneburg Bockelsberg 3
# Lüneburg Bockelsberg 5

来自官方文件:

>>> u = unichr(40960) + u'abcd' + unichr(1972)   # Assemble a string
>>> utf8_version = u.encode('utf-8')             # Encode as UTF-8
>>> type(utf8_version), utf8_version
(<type 'str'>, '\xea\x80\x80abcd\xde\xb4')
>>> u2 = utf8_version.decode('utf-8')            # Decode using UTF-8
>>> u == u2                                      # The two strings match
True
© www.soinside.com 2019 - 2024. All rights reserved.