-4

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
4

3 回答 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'
于 2013-11-12T13:27:49.890 回答
1

如果您只需要它作为新字符串,那么为什么不呢:

import re
s = "my_data [0.046, 0.028, 0.01]"
print re.sub("[\[\],]", "", s)
于 2013-11-12T13:49:09.193 回答
0

这似乎比其他解决方案更具可读性:

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

这可以被压缩成一个单行,但它看起来并不优雅/简单:

s = "my_data [0.046, 0.028, 0.01]".replace('[', '').replace(']', '').replace(',', '')
于 2013-11-12T14:17:26.997 回答