删除特定字符集?

2024-09-29 23:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这样的密码

translated1 = str(''.join( c for c in translated2 if c not in "[']" ))

将删除[或'或]的任何实例,但如何对其进行编码,使其完全删除“--”这个

我不想删除“-”的任何实例,只要这3个实例同时在一起

我该怎么做?谢谢你


Tags: 实例in密码编码forifnotjoin
2条回答

您可以使用str.replace(patt, repl)

s = " -test test-test  "
print(s.replace(" -", ""))
# "test test-test-"

如果您想要更具可扩展性的东西,也可以使用re来实现

这可以很容易地通过正则表达式来实现。 您可以阅读有关python正则表达式here的更多信息

你可以这样用-

import re
str1 = 'there is three  - and now single - and now two  '
str2 = re.sub(' -', '', str1)
print(str2)

输出-

there is three  and now single - and now two  

DEMO

相关问题 更多 >

    热门问题