Reputation: 2495
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]'
Upvotes: 3
Views: 164
Reputation: 12438
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]
Upvotes: 2
Reputation: 520908
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]
Upvotes: 3