【发布时间】:2021-03-22 19:40:30
【问题描述】:
我一直在尝试学习如何删除随机给定字符串上的特殊字符。一个随机给定的字符串可能是这样的:
uh\n haha - yes 'nope' \t tuben\xa01337
我同时使用了正则表达式和string.translate 来尝试对我有用的方法:
import re
random_string = "uh\n haha - yes 'nope' \t tuben\xa01337"
print(re.sub(r"/[' \n \t\r]|(\xa0)/g", '', random_string))
print("-------")
print(random_string.translate(str.maketrans({c: "" for c in "\n \xa0\t\r"})))
返回的输出:
uh
haha - yes 'nope' tuben 1337
-------
uhhaha-yes'nope'tuben1337
问题是它不能按我的意愿工作,因为我希望输出是:
uh haha - yes nope tuben 1337
我想知道我怎么能做到这一点?
- \n\t\xa0 或任何类似内容应替换为一个空格
- ' 和 " 应该替换为没有空格,只需删除 ' 和 "
- 双空格或更多空格应替换为总共只有一个空格。这意味着如果文本中有两个或多个空格,则应将其替换为一个。
- 任何特殊字符也应删除
【问题讨论】:
-
Python 正则表达式周围没有
/。
标签: python python-3.x regex replace