[英]How to replace all square brackets and their values with empty strings?
如果您不知道有多少个方括号,如何用空字符串替换所有方括号及其值?
data = "[a] 1 [b] test [c] other characters"
我希望数据是" 1 test other characters"
。
您可以使用正则表达式在括号部分拆分字符串:
import re
data = "[a] 1 [b] 2 [c]"
parts = re.split(r'\[.*?\]', data)
# ['', ' 1 ', ' 2 ', '']
out = '[' + ' '.join(parts) + ']'
print(out)
# [ 1 2 ]
另一个冗长的答案是:
import re
data = "[a] 1 [b] test [c] other characters"
pattern = '\[.*?\]' #any character(s) with [ ]
unwanted = set(re.findall(pattern,data))
results = ' '.join(i for i in data.split()
if i not in unwanted)
print(results)
# 1 test other characters
更新
加法条件
问题 > “[a] 1 [b] test [1] other [c]haracters” 由于.split()
这不会被替换
import re
data = "[a] 1 [b] test [1] other [c]haracters"
pattern = '\[.*?\]' #any character(s) with [ ]
print(re.sub(pattern,'',data))
# " 1 test other haracters"
删除多余的空格
_ = re.sub(pattern,'',data).split()
print(' '.join(i for i in _ if i))
# "1 test other haracters"
尝试正则表达式替代。
import re
data = "[a] 1 [b] 2 [c]"
new = re.sub("([[a-z]*])", "", data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.