从用户输入的字符串中删除UTF-8

时间:2017-06-20 21:44:54

标签: python utf-8

有没有办法在不使用任何导入方法的情况下从字符串中删除UTF-8符号?

例如:

userString = "apples, pears \xc2\xa7 and bananas\ngrapes\nbananas !apples"

期望的输出:

userString = "apples, pears  and bananas\ngrapes\nbananas !apples"

1 个答案:

答案 0 :(得分:0)

使用bytes转换str对象可以指定如何处理编码错误,因此您可以忽略它们:

>>> userString = b"apples, pears \xc2\xa7 and bananas\ngrapes\nbananas !apples"
>>> str(userString, "ascii", errors="ignore")
'apples, pears  and bananas\ngrapes\nbananas !apples'