-5

What is the easiest method to convert following string:

s = "my_data [0.046, 0.028, 0.01]"

into the string exactly as below:

my_data 0.046 0.028 0.01
3
  • 4
    That input is not valid Python code. Do you get it as a string?
    – user1907906
    Nov 12, 2013 at 13:25
  • @Nirock Then you haven't seen much :p
    – user1907906
    Nov 12, 2013 at 13:27
  • 2
    @nils So what have you tried so far?
    – user1907906
    Nov 12, 2013 at 13:27

3 Answers 3

4
s = "my_data [0.046, 0.028, 0.01]"
" ".join(i.strip("[,]") for i in s.split(" "))
# output: 'my_data 0.046 0.028 0.01'
1

This seems slightly more readable than the other solutions:

s = "my_data [0.046, 0.028, 0.01]"
for replacer in ('[', ']', ','):
    s = s.replace(replacer, '')

This can be compressed into a one-liner, but it doesn't seem as elegant/simple:

s = "my_data [0.046, 0.028, 0.01]".replace('[', '').replace(']', '').replace(',', '')
1

If you just need it as a new string, then why not:

import re
s = "my_data [0.046, 0.028, 0.01]"
print re.sub("[\[\],]", "", s)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.