如何删除“[”使用 re.sub 函数从字符串中提取字符?

发布于 2025-01-19 03:10:48 字数 314 浏览 2 评论 0原文

我想从字符串中删除“[”方括号字符。 我正在使用 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']

I want to remove the '[' square bracket character from a string.
I am using re library.
I had no problems with this square bracket ']' but I still having problem with this square bracket '['.

My code:

depth_split = ['[575,0]']

new_string = re.sub(']','',depth_split) #working
newnew_string = re.sub('[','',new_string) #not working

PS: I'm using python.

The output that I have : ['[575,0']

The output that I expeting : ['575,0']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遗忘曾经 2025-01-26 03:10:48

在这里不需要使用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)

There is no need of using regex here since it can be done easily using str.replace():

new_string= '[575,0]'
new_string = new_string.replace(']', '')
new_string = new_string.replace('[', '')
print(new_string)

But if using regex is necessary try:

import re

depth_split = '[575,0]'

new_string = re.sub(r'\]|\[','',depth_split) #working
print(new_string)
℡Ms空城旧梦 2025-01-26 03:10:48

您似乎想要的正则表达式模式是 ^\[|\]$

depth_split = ['[575,0]']
depth_split[0] = re.sub(r'^\[|\]
, '', depth_split[0])
print(depth_split)  # ['575,0']

The regex pattern you seem to want here is ^\[|\]$:

depth_split = ['[575,0]']
depth_split[0] = re.sub(r'^\[|\]
, '', depth_split[0])
print(depth_split)  # ['575,0']
北笙凉宸 2025-01-26 03:10:48

如果支架始终处于列表中字符串的开始和结尾,则可以使用字符串切片进行以下操作:

depth_split = ['[575,0]']

depth_split = [e[1:-1] for e in depth_split]

print(depth_split)

output:

['575,0']

If the brackets are always at the beginning and end of the strings in your list then you can do this with a string slice as follows:

depth_split = ['[575,0]']

depth_split = [e[1:-1] for e in depth_split]

print(depth_split)

Output:

['575,0']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文