0

I have data in python that needs to convert string from

string = "[-8.27104300e-02  9.09485668e-02  7.72242993e-02]"

to this

converted_string = "-8.27104300e-02, 9.09485668e-02, 7.72242993e-02"

Basically removing brackets [] and putting in comma for the spaces

How do I achieve this ?

2
  • This doesn't require regex at all. This is a simple string slicing operation to remove the brackets, and then a str.replace call to replace 2 spaces with a comma and a space. Commented Jan 29, 2018 at 1:01
  • @Rawing It may or may not, depending on whether the space width is fixed or not. Commented Jan 29, 2018 at 1:18

1 Answer 1

1

You don't need regex for removing the braces. That's just a simple slicing operation. However, I could see the need for it when substituting whitespace, especially when you have varying width whitespace separators.

>>> import re
>>> re.sub('\s+', ', ', string[1:-1])

'-8.27104300e-02, 9.09485668e-02, 7.72242993e-02'

However, if you can guarantee a fixed separator width of 2 spaces, then str.replace works well here -

>>> string[1:-1].replace('  ', ', ')
'-8.27104300e-02, 9.09485668e-02, 7.72242993e-02'
Sign up to request clarification or add additional context in comments.

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.