python string替换不起作用

时间:2017-04-26 07:35:43

标签: python string replace

我有一个包含令牌的列表列表。一些令牌包含我想用空格替换的特殊字符。但是我的代码没有用:

mylist = [['hi','how','are','you','forward\xcato\xcahearing\xcafrom\xcayou\xcasoon'],
          ['good','morning']]

mycode的:

new_list = []
for l in mylist:
    l2 = [i.replace('\xca', ' ') for i in l]
    new_list.append(l2)
new_list[0]
>>> ['hi','how','are','you','forward\xcato\xcahearing\xcafrom\xcayou\xcasoon']

不确定为什么它不起作用。

2 个答案:

答案 0 :(得分:0)

这也适用于Jupyter:

mylist = [['hi','how','are','you','forward\xcato\xcahearing\xcafrom\xcayou\xcasoon'],
          ['good','morning']]

print ([[sentence.translate(str.maketrans("\xca", " ")) for sentence in item] for item in mylist])

答案 1 :(得分:0)

我的代码将删除字符串中的所有特殊字符!不只是' \ xca'你会有一个修剪字符串。 (没有图书馆需要):

your_list = [['hi','how','are','you','forward\xcato\xcahearing\xcafrom\xcayou\xcasoon'],
['good','morning']]


def special_characters_finder(text):

    renew_word = []

    for char in text:
        try:
            char.encode('ascii')

        except UnicodeEncodeError:
            renew_word.append(' ')

        else:
            renew_word.append(char)

    return ''.join(renew_word)


buffer_output = []
for box in your_list:
    for item in box:
        get_list = special_characters_finder(item)
        buffer_output.append(get_list)

print(buffer_output)

输出:

['hi', 'how', 'are', 'you', 'forward to hearing from you soon', 'good', 'morning']