python - 从字符串中删除由字符分隔的特殊符号

标签 python python-3.x

仅当特殊符号 /#$%^&*@0123456789 彼此之间被不在列表中的字符或符号分隔时,如何删除它们。例如:

H8e%&l6&%l@8095o a@/9^65$n228d w%e60$$#&9l3@/c6o5m3e --> Hello and welcome
. #$%#^ --> . #$%#^
,. a3%2%1/3$s*0. d8^! -->,. as. d!
I1^/0^^@9t #$%% i/@4#s 11P17/9$M 5^&* a^$45$5$0n&##^4d 6^&&* I $%^$%^ a8@@94%3*m t3120i36&^1r2&^##0e&^d ---> It #$%% is 11PM 5^&* and 6^&&* I $%^$%^ am tired

我知道简单的 string.replace 在这里不起作用。我尝试了类似的方法,但它也不起作用:

 def _correct_message(message):
    f = re.match(r'[a-zA-Z][/#$%^&*@0123456789​][a-zA-Z]', message)
    if f is not None:
        message = re.sub('[/#$%^&*@0123456789​]', '', message)

最佳答案

你可以试试这个:

import re
s = "H8e%&l6&%l@8095o a@/9^65$n228d w%e60$$#&9l3@/c6o5m3e" 
s1 = "I1^/0^^@9t #$%% i/@4#s 11P17/9$M 5^&* a^$45$5$0n&##^4d 6^&&* I $%^$%^ a8@@94%3*m t3120i36&^1r2&^##0e&^d"
final_string = re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', s) 
print(final_string)
new_final_string = re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', s1)
print(new_final_string)
print(re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', ',. a3%2%1/3$s*0. d8^!'))

输出:

'Hello and welcome'
It #$%% is 11PM 5^&* and 6^&&* I $%^$%^ am tired
,. as. d!

关于python - 从字符串中删除由字符分隔的特殊符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47145666/

相关文章:

python - 为什么我的抓取 NSE 网站的程序在服务器中被阻止,但在本地却可以运行?

python - 加载预训练模型 pytorch - dict 对象没有属性 eval

python - 由于权限原因,无法使用 libusb 读取 USB 字符串描述符

Python - 转置各种长度列表的列表 - 3.3 最简单​​的方法

python-3.x - Keras 在每个 epoch 中占用的内存量无限增加

python-3.x - Cron 作业中的 PyAutoGUI

python - python中的类型模仿

python - 当值通过循环进入时,字典 0 键值未被拾取

python - 包内显式相对导入不使用关键字 from

python - 如何从 Android 应用程序连接到 Odoo 数据库