为什么不能删除此字符串中的空格?

2024-09-30 20:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

s = '种草 ​'
print(len(s))
s = s.strip()
print(len(s))

两者的输出都是“4”。似乎空格占用了2个字符,无法通过strip()函数删除。这是一个中文空间,不能用strip函数删除


Tags: 函数len空间strip空格print个字符种草
3条回答

strip从字符串的两端删除空格

>>> s = '种草 ​'
>>> ord(s[-1])
8203
>>> ord(s[-2])
32
>>> ord(' ')
32

这里的最后一个字符不是空格字符。最后的第二个字符是空格

可能这不是一个好看的解决方案,但它将剥离所有不可打印和空白字符:

from itertools import takewhile

check = lambda c: not c.isprintable() or c.isspace()

result = s[len(tuple(takewhile(check, s))): -len(tuple(takewhile(check, reversed(s))))]
# OR to not waste memory for tuple
result = s[sum(1 for _ in takewhile(check, s)): -sum(1 for _ in takewhile(check, reversed(s)))]

在这里,我使用^{}从字符串开始获取所有不可打印(^{})和空格(^{})字符。然后使用^{}(或带有列表理解的选项中的^{}),我得到了诸如字符的数量,并将该数量用作字符串切片中的开始索引。为了获得结束索引,我使用了相同的方法,但使用了反向(^{})字符串

它不是一个普通的unicode空间。你可以这样取下它

s = '种草 ​'
print(len(s))
s = s.strip(u'\u200b').strip()
print(len(s))

相关问题 更多 >