Skip to main content
 首页 » 编程设计

python之字符串中出现非 ASCII 字符

2025年05月04日26mfrbuaa

所以我需要比较 2 个 strings :

str1 = 'this is my string/ndone' 
str2 = 'this is my string done' 

所以我将 str1 中的新行替换为 ' ':

new_str = str1.replace('\n', ' ') 

当打印 2 个字符串时,它们是相同的:

'this is my string done' 

但是当使用 == 运算符进行比较时,我将这 2 个字符串转换为数组以查看它们为什么不相等:

arr1 = bytearray(str1 , 'utf-8') 
print(arr1) 
 
arr2 = bytearray(str2 , 'utf-8') 
print(arr2) 

这是输出:

str1 = bytearray(b'this is\xc2\xa0my string done') 
 
str2 = bytearray(b'this is my string done') 

那么这个 \xc2\xa0 是什么?

请您参考如下方法:

'\xc2\xa0'是Unicode字符'NO-BREAK SPACE' (U+00A0)的UTF-8编码.