我想從字串中洗掉 '[' 方括號字符。我正在使用 re 庫。我對這個方括號 ']' 沒有任何問題,但我仍然對這個方括號 '[' 有問題。
我的代碼:
depth_split = ['[575,0]']
new_string = re.sub(']','',depth_split) #working
newnew_string = re.sub('[','',new_string) #not working
PS:我正在使用python。
我的輸出:['[575,0']
我的輸出:['575,0']
uj5u.com熱心網友回復:
這里不需要使用regex,因為它可以很容易地使用str.replace():
new_string= '[575,0]'
new_string = new_string.replace(']', '')
new_string = new_string.replace('[', '')
print(new_string)
但如果regex需要使用,請嘗試:
import re
depth_split = '[575,0]'
new_string = re.sub(r'\]|\[','',depth_split) #working
print(new_string)
uj5u.com熱心網友回復:
您似乎想要的正則運算式模式是^\[|\]$:
depth_split = ['[575,0]']
depth_split[0] = re.sub(r'^\[|\]$', '', depth_split[0])
print(depth_split) # ['575,0']
uj5u.com熱心網友回復:
如果括號始終位于串列中字串的開頭和結尾,則可以使用字串切片執行此操作,如下所示:
depth_split = ['[575,0]']
depth_split = [e[1:-1] for e in depth_split]
print(depth_split)
輸出:
['575,0']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455718.html
上一篇:在字串串列中查找公共字串C#
