拆分不含非字符的字符串
我正在尝试分割一个看起来像这样的字符串,例如:
':foo [bar]'
对此使用 str.split()
当然会返回 [':foo','[bar]']
我怎样才能让它返回只包含这些字符的 ['foo','bar']
呢?
I'm trying to split a string that looks like this for example:
':foo [bar]'
Using str.split()
on this of course returns [':foo','[bar]']
But how can I make it return just ['foo','bar']
containing only these characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不喜欢正则表达式,但喜欢 Python,所以我可能会写成
“”.join 习惯用法有点奇怪,我承认,但你几乎可以用英语阅读其余部分:“join every character for如果字符是字母数字或字符是空格,则分割 s 中的字符,然后将其拆分”。
或者,如果您知道要删除的符号始终位于外部,并且单词仍将由空格分隔,并且您知道它们是什么,您可以尝试类似的操作
I don't like regular expressions, but do like Python, so I'd probably write this as
The ''.join idiom is a little strange, I admit, but you can almost read the rest in English: "join every character for the characters in s if the character is alphanumeric or the character is whitespace, and then split that".
Alternatively, if you know that the symbols you want to remove will always be on the outside and the word will still be separated by spaces, and you know what they are, you might try something like
照常执行
str.split()
,然后解析每个元素以删除非字母。像这样的东西:Do
str.split()
as normal, and then parse each element to remove the non-letters. Something like:您必须使用正则表达式遍历列表
['foo','[bar]']
并删除所有非字母字符。检查正则表达式替换(在Python中)-更简单的方法?示例和文档参考。You'll have to pass through the list
['foo','[bar]']
and strip out all non-letter characters, using regular expressions. Check Regex replace (in Python) - a simpler way? for examples and references to documentation.您必须尝试正则表达式。
使用 re.sub() 替换
:,[, ]
字符,然后使用空格
作为分隔符分割结果字符串。You have to try regular expressions.
Use re.sub() to replace
:,[,]
characters and than split your resultant string withwhite space
as delimiter.