Skip to main content
 首页 » 编程设计

python之替换列表中的空格

2025年05月04日12del

我想替换我的字符串

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 方法来做到这一点?

请您参考如下方法:

试试这个:

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'