Python 2.7,Umlauts,UTF-8和列表

时间:2015-10-20 08:43:14

标签: python list utf-8

我尝试使用Python 2.7将一堆文件名中的德语变音符号替换为其他字符。我使用以下代码获取名称中带有变音符号的所有文件的列表:

# -*- coding: utf-8 -*-

import os

def GetFilepaths_umlaut(directory):
    file_paths = [] 
    umlauts = ["Ä", "Ü", "Ö", "ä", "ö", "ü"]
    for root, directories, files in os.walk(directory):
        for filename in files:
            filepath = os.path.join(root, filename)
            if any(umlaut in filepath for umlaut in filepath):
                file_paths.append(filepath)
    print file_paths
    return file_paths

GetFilepaths_umlaut(r'C:\Scripts\Replace Characters\Umlauts')

但是当列表打印到控制台时,它不会打印变音符号(见截图)。我尝试过使用encode()但是我收到了第二个屏幕截图中显示的错误。我究竟做错了什么?非常感谢任何反馈!

enter image description here

在文件路径上使用encode(): enter image description here

1 个答案:

答案 0 :(得分:1)

print file_paths正在打印列表,而不是字符串。对于输出的显示方式,由list对象的str()和/或unicode()方法决定。在这种情况下,使用转义字符串打印列表的元素:

>>> s = u'a\xe4a'
>>> s
u'a\xe4a'
>>> print s
aäa
>>> [s]
[u'a\xe4a']
>>> print [s]
[u'a\xe4a']

打印实际字符串:

for s in file_paths:
    print s
相关问题