Skip to main content
 首页 » 编程设计

python之删除字母Python之间的符号

2025年05月04日10qq78292959

我想从字符串中删除某些符号。我只想删除字母之间的符号。如果我的问题不够清楚,那么这里有一些例子: 符号是 @31!

输入

@@He11o Wor1d! 
!!T3ach !m3 
@13! 

预期输出

@@Heo Word! 
!!Tach !m3 
@13! 

你能给我指出正确的方向吗?我不指望你为我做这件事。我知道这可以用正则表达式和 for 循环来完成,但正则表达式对于像我这样的初学者来说似乎有点困难。这是我现在正在做的事情:

string = '@@He11o Wor1d!' 
string_copy = string 
symbols = "@31!" 
for char in symbols: 
    string_copy = string_copy.replace(char, "") 

我知道这个脚本会替换所有符号

请您参考如下方法:

Regular expressions一开始肯定很可怕,但值得尝试学习它们,因为它们最终会非常有用。在这种情况下你想要的是:

import re 
string = re.sub(r'([a-zA-Z])[@31!]+(?=[a-zA-Z])', r'\1', string) 

Let's look at what this does.

re.sub类似于str.replace,但它使用正则表达式。

[a-zA-Z] 匹配任何字母。

[@31!]+ 匹配一个或多个列出的符号。

+ causes the resulting RE to match 1 or more repetitions of the preceding RE.

(?=[a-zA-Z]) 是字母的先行断言。这意味着匹配后跟一个字母,但字母不是匹配的一部分。

(?=...) matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

因此 ([a-zA-Z])[@31!]+(?=[a-zA-Z]) 匹配一个字母后跟列表中的一个或多个符号。此匹配后跟一个字母,但匹配不包括该字母。

\1 是对正则表达式中带括号的组的反向引用,在本例中为 [a-zA-Z]。这就是我们想要替换我们发现的东西。

(字符串前的 r 是为了使它们成为原始字符串,这在使用正则表达式时通常很有帮助。)

编辑:

正如@ctwheels 指出的那样,you can also use a lookbehind assertion rather than a backreference :

string = re.sub(r'(?<=[a-zA-Z])[@31!]+(?=[a-zA-Z])', r'', string)