如何替换/删除字符串的一部分,如
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)
如果括号内字符串的长度是固定的,则可以使用切片来获取内部子字符串:
(
string[9:-9]
如果要删除周围的空格)如果硬编码索引感觉不好,可以使用str.index派生它们(如果可以确定字符串不会包含嵌入的'}'):
使用
re
库执行regex替换,如下所示:此代码有效
string = '{DDBF1F} this is my string {DEBC1F}' st=string.split(' ') new_str='' for i in st: if i.startswith('{') and i.endswith('}'): pass else: new_str=new_str+" "+ i print(new_str)
相关问题 更多 >
编程相关推荐