简体   繁体   English

Python从字符串中删除动态子字符串

[英]Python remove dynamic substring from string

I need to remove dynamic substring from string. 我需要从字符串中删除动态子字符串。 eg: 例如:

Item value1="001" value2="abc" value3="123xyz"

and i need output: 我需要输出:

Item value1="001"  value3="123xyz"

I mean I need remove value2="abc". 我的意思是我需要删除value2 =“ abc”。 value2 is an unique element and can be placed anywhere in original string. value2是一个唯一元素,可以放在原始字符串的任何位置。 "abc" is dynamic variable and can have various length. “ abc”是动态变量,可以具有各种长度。 What is the fastest solution of this problem? 解决这个问题最快的方法是什么? Thank you. 谢谢。

regex should be pretty fast in this case: regex在这种情况下应该非常快:

import re
p = re.compile(r'value2="\w+"\s?')
re.sub(p, '', 'Item value1="001" value2="abc" value3="123xyz"')

the above works assuming the value for value2 has only alphabets (ie no digits or space-like charaters 上面的工作假设value2的值只有字母(即没有数字或空格字符)

You could try a list comprehension 您可以尝试列表理解

a='Item value1="001" value2="abc" value3="123xyz"'
print(' '.join([e for e in a.split(" ") if not e.startswith('value2="')]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM