[英]Split a string into characters excluding the whitespace
我有一个代码:
import re
def sam(str)
data=re.split(r'(\w)',str)
print data
if __name__== "__main__":
sam('hello how are you')
我得到的输出是:
["","h","e","l","l","o","","h","o","w",""....]
我想分割这些单词的每个字符(不包括空格)。 我如何获得以下输出:
["h","e","l","l","o","h","o","w",....]
区别在于没有空白/空白条目。
[char for char in string if not char.isspace()]
或者,如果您只关心ASCII空格字符,而不是所有空格,
list(string.replace(' ', ''))
或者如果您真的只想保留与\\w
匹配的字符:
re.findall(r'\w', string)
findall
版本仅保留字母,数字和下划线。 如果这是您想要的,请继续使用。
使用str.replace
:
In [805]: list(s.replace(' ', ''))
Out[805]: ['h', 'e', 'l', 'l', 'o', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u']
或str.translate
:
In [808]: list(s.translate(None, ' '))
Out[808]: ['h', 'e', 'l', 'l', 'o', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u']
在处理长字符串时,它们比列表理解(如@ user2357112所述)快几倍:
In [827]: s2='hello how are you'*10000
In [828]: timeit [char for char in s2 if not char.isspace()]
100 loops, best of 3: 19.5 ms per loop
In [889]: timeit [char for char in s2 if char != ' ']
100 loops, best of 3: 14 ms per loop
In [829]: timeit list(s2.replace(' ', ''))
100 loops, best of 3: 3.4 ms per loop
In [830]: timeit list(s2.translate(None, ' '))
100 loops, best of 3: 2.87 ms per loop
只需使用list和replace ,这里不需要任何正则表达式。
>>> list('hello how are you'.replace(' ', ''))
['h', 'e', 'l', 'l', 'o', 'h', 'o', 'w', 'a', 'r', 'e', 'y', 'o', 'u']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.