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

2024-10-01 04:44:19 发布

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

如何替换/删除字符串的一部分,如

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)

Tags: the字符串onlystringismycodeit
3条回答

如果括号内字符串的长度是固定的,则可以使用切片来获取内部子字符串:

>>> string = '{DDBF1F} this is my string {DEBC1F}'
>>> string[8:-8]
' this is my string '

string[9:-9]如果要删除周围的空格)

如果硬编码索引感觉不好,可以使用str.index派生它们(如果可以确定字符串不会包含嵌入的'}'):

>>> start = string.index('}')
>>> start
7
>>> end = string.index('{', start)
>>> end
27
>>> string[start+1:end]
' this is my string '

使用re库执行regex替换,如下所示:

import re

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

此代码有效

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)

相关问题 更多 >