簡體   English   中英

如何用空字符串替換所有方括號及其值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM