0

I need to remove dynamic substring from string. e.g.:

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

and i need output:

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

I mean I need remove value2="abc". value2 is an unique element and can be placed anywhere in original string. "abc" is dynamic variable and can have various length. What is the fastest solution of this problem? Thank you.

4
  • 1
    What have you tried so far? Commented Jun 26, 2018 at 19:48
  • I tagged this with regex. Soon the regex-sharks come. Commented Jun 26, 2018 at 19:50
  • Do you really need the fastest solution? Because writing custom C code is going to beat any regex or str-method solution, even if only by a few nanoseconds, but does that actually matter? Commented Jun 26, 2018 at 19:56
  • Regular expression is also fine Commented Jun 26, 2018 at 20:03

2 Answers 2

1

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="')]))
Sign up to request clarification or add additional context in comments.

1 Comment

not e.startswith('value2=') should be a little faster in this approach
1

regex should be pretty fast in this case:

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 (i.e. no digits or space-like charaters

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.