Skip to main content
 首页 » 编程设计

python之如何在 python 中替换/删除字符串

2025年05月04日14落叶

我怎样才能像这样替换/删除字符串的一部分

string = '{DDBF1F} this is my string {DEBC1F}' 
#{DDBF1F} the code between Parentheses is random, I only know it is made out of 6 characters 

输出应该是

this is my string 

我试过了,我知道它行不通,但我试过了:3

string = '{DDBF1F} Hello {DEBC1F}' 
string.replace(f'{%s%s%s%s%s%s}', 'abc') 
print(string) 

请您参考如下方法:

使用 re 库执行正则表达式替换,如下所示:

import re 
 
text = '{DDBF1F} Hello {DEBC1F}' 
result = re.sub(r"(\s?\{[A-F0-9]{6}\}\s?)", "", text) 
print(result)