3

I have a string and I want to clean it, for that I am using multiple replace commands.

Is there a better way to do it?

a = '[[<Package 9.00x6.00x5.60>, <Package 8.75x6.60x5.60>]]'

a.replace("[<Package ","").replace(">]","").replace("<Package ","").replace(">","")

Result:

'[9.00x6.00x5.60, 8.75x6.60x5.60]'

2 Answers 2

3

Try using re.sub:

a = '[[<Package 9.00x6.00x5.60>, <Package 8.75x6.60x5.60>]]'
output = re.sub(r'<Package ([^>]+)>', r'\1', a)
# remove outer [] brackets
output = output[1:-1]
print(output)

[9.00x6.00x5.60, 8.75x6.60x5.60]
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use the following approach:

import re

a = '[[<Package 9.00x6.00x5.60>, <Package 8.75x6.60x5.60>]]'
output = '[' + ''.join(re.split('[><[\]]|Package ',a)) + ']'
print(output)

where you split your string in a list using the delimiters: >, <, ], [, Package then you concatenate the result in a string and add the outer brackets.

output:

[9.00x6.00x5.60, 8.75x6.60x5.60]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.