每当我看到编码差异时,如何遍历字符串并插入空格?例如,输入:
Bar bar black sheep就是其中 famous 的一家club
应该产生这个输出:
Bar bar black sheep 就是其中 famous 的一家 club
我尝试了以下方法,但有没有更简单的方法来执行以下操作?
# -*- coding: utf8 -*-
sentence = 'Bar bar black sheep就是其中 famous 的一家club'
currIsAscii = None
prevIsAscii = None
newsentence = ""
for i in sentence:
try:
i.decode('ascii')
currIsAscii = True
except:
currIsAscii = False
if prevIsAscii != currIsAscii:
newsentence+=" "
newsentence+=i
else:
newsentence+=i
prevIsAscii = currIsAscii
while " " in newsentence:
newsentence = newsentence.replace(" ", " ")
print newsentence.strip()