Python从字符串列表中删除空格变体的最佳实践

2024-09-29 20:29:25 发布

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

在Python中,有没有从字符串中删除奇怪的空格unicode字符的最佳实践

例如,如果一个字符串在这个table中包含以下Unicode之一,我想删除它

我想把unicodes放到一个列表中,然后用replace做一个循环,但我相信有一种更符合python的方法


Tags: 方法字符串列表tableunicode字符replace空格
2条回答

你应该能够使用这个

[''.join(letter for letter in word if not letter.isspace()) for word in word_list] 

因为如果你阅读^{}的文档,它会说:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

如果您查看类别Zsunicode character list

在这种情况下,Regex是您的朋友,您可以简单地应用Regex替换来迭代列表

import re
r = re.compile(r"^\s+")

dirty_list = [...]
# iterate over dirty_list substituting
# any whitespace with an empty string
clean_list = [
  r.sub("", s)
  for s in dirty_list
]

相关问题 更多 >

    热门问题