替换列表中的空格

时间:2019-03-05 08:06:20

标签: python python-3.x string replace formatting

我要替换my_string

my_string = '[[4.6, 4.3, 4.3], [8.75, 5.6, 6.6], [4.6, 4.3, 4.3]]'

使得它给出这样的结果

my_string = '4.6x4.3x4.3 8.75x5.6x6.6 4.6x4.3x4.3'

我已经尝试过了,但这也用“ x”填充了空白

mystring = mystring.replace("[","").replace("]","").replace(", ","x")

是否有更好的pythonic方法来做到这一点?

5 个答案:

答案 0 :(得分:6)

尝试一下:

import ast
my_string = '[[4.6, 4.3, 4.3], [8.75, 5.6, 6.6], [4.6, 4.3, 4.3]]'
mystring = " ".join(["x".join([str(k) for k in i]) for i in ast.literal_eval(my_string)])
# mystring = '4.6x4.3x4.3 8.75x5.6x6.6 4.6x4.3x4.3'

答案 1 :(得分:2)

您可以使用正则表达式提取子列表的内容:

import re

s = '[[4.6, 4.3, 4.3], [8.75, 5.6, 6.6], [4.6, 4.3, 4.3]]'

' '.join(i.replace(', ', 'x') for i in re.findall(r'\[([^\[\]]+)\]', s))
# 4.6x4.3x4.3 8.75x5.6x6.6 4.6x4.3x4.3

答案 2 :(得分:1)

],分割它,然后做你已经在做的事情:

my_string = '[[4.6, 4.3, 4.3], [8.75, 5.6, 6.6], [4.6, 4.3, 4.3]]'

for e in my_string.split("],"):
    print(e.replace("[","").replace("]","").replace(", ","x"), end = "")

输出

4.6x4.3x4.3 8.75x5.6x6.6 4.6x4.3x4.3

答案 3 :(得分:1)

您可以使用此:

import ast
str = '[[4.6, 4.3, 4.3], [8.75, 5.6, 6.6], [4.6, 4.3, 4.3]]'
my_list = ast.literal_eval(str)
result = ' '.join(['x'.join("{}".format(item) for item in sub_list) for sub_list in my_list])
print(result)

enter image description here

答案 4 :(得分:1)

您可以直接使用eval,而无需导入ast。

my_string = '[[4.6, 4.3, 4.3], [8.75, 5.6, 6.6], [4.6, 4.3, 4.3]]'
my_list = eval(my_string)
result = ' '.join(['x'.join("{}".format(item) for item in sub_list) for sub_list in my_list])

输出

'4.6x4.3x4.3 8.75x5.6x6.6 4.6x4.3x4.3'