[英]Python - remove parts of a string
我在字符串中有很多空白的句子,
例如: "6d) We took no [pains] to hide it ."
我如何有效地解析此字符串(在Python中)为
"We took no to hide it"?
我还希望能够将该单词存储在列表中的方括号(例如“疼痛”)中,以备后用。 我认为regex模块可能比split()这样的Python字符串操作更好。
这将为您提供方括号内的所有单词。
import re
s="6d) We took no [pains] to hide it ."
matches = re.findall('\[(.*?)\]', s)
然后,您可以运行此命令以删除所有带括号的单词。
re.sub('\[(.*?)\]', '', s)
只是为了好玩(一次迭代收集和替换)
matches = []
def subber(m):
matches.append(m.groups()[0])
return ""
new_text = re.sub("\[(.*?)\]",subber,s)
print new_text
print matches
import re
s = 'this is [test] string'
m = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print m.group(1)
输出量
'test'
对于您的示例,您可以使用此正则表达式:
(.*\))(.+)\[(.+)\](.+)
您将获得四个组,可用于创建结果字符串并保存3.组以供以后使用:
6d)
We took no
pains
to hide it .
我在这里使用.+
是因为我不知道您的字符串是否总是像您的示例一样。 您可以将.+
更改为字母数字或sth。 更特殊的情况。
import re
s = '6d) We took no [pains] to hide it .'
m = re.search(r"(.*\))(.+)\[(.+)\](.+)", s)
print(m.group(2) + m.group(4)) # "We took no to hide it ."
print(m.group(3)) # pains
import re
m = re.search(".*\) (.*)\[.*\] (.*)","6d) We took no [pains] to hide it .")
if m:
g = m.groups()
print g[0] + g[1]
输出:
我们毫不掩饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.