Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python动态删除字符串的元素_Python_Regex - Fatal编程技术网

Python动态删除字符串的元素

Python动态删除字符串的元素,python,regex,Python,Regex,我有以下文字 TextTextlkwhcuiachjwhdehwkjfchjwfbhjwvfbgAGE18 hjweghwvf wffguh wygfyugf hAGE29 kjefrhjefherbfhjefb AGE30 我怎样才能使它成为 TextTextlkwhcuiachjwhdehwkjfchjwfbhjwvfbg hjweghwvf wffguh wygfyugf h kjefrhjefherbfhjefb ?? 所以用零替换AGEXXX?这正是正则表达式的用途 import

我有以下文字

TextTextlkwhcuiachjwhdehwkjfchjwfbhjwvfbgAGE18 hjweghwvf wffguh wygfyugf hAGE29 kjefrhjefherbfhjefb AGE30
我怎样才能使它成为

TextTextlkwhcuiachjwhdehwkjfchjwfbhjwvfbg hjweghwvf wffguh wygfyugf h kjefrhjefherbfhjefb 
??
所以用零替换AGEXXX?

这正是正则表达式的用途

import re
re.sub(r'AGE\d+', '', my_string)

尝试
re
库。这是Python版本的正则表达式:

import re
new_string = re.sub(r'AGE\d{2,3}', '', string) 

其中,
string
是您的输入,
new\u string
是不带“AGEXXX”的字符串

str
在某些方面的行为类似于
列表
s:

string = "TextTextlkwhcuiachjwhdehwkjfchjwfbhjwvfbgAGE18 hjweghwvf wffguh wygfyugf hAGE29 kjefrhjefherbfhjefb AGE30"
word = "AGE"
extra_chars = 2

while word in string:
    string = string[:string.index(word)] + string[string.index(word)+len(word)+extra_chars:]
这是一种简单的方法,对于默认为
re
模块的更复杂的解决方案