繁体   English   中英

替换和删除字符串中的项目

[英]Replace and remove items from a string

我要替换my_string

my_string = '[[4.6, 4.3, 4.3, 85.05], [8.75, 5.6, 6.6, 441.0], [4.6, 4.3, 4.3, 85.9625]]'

这样它就给出这样的结果

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

last_item = '85.05 441.0 85.9625'

列表中的最后一项没有固定的长度对于我写的第一个目标

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

但是我需要一种更Python化的方式。

如果my_string = '[[4.6, 4.3, 4.3, 85.05], [8.75, 5.6, 6.6, 441.0], [4.6, 4.3, 4.3, 85.9625]]'

import ast
my_string = " ".join(["x".join([str(k) for k in i[:-1]]) for i in ast.literal_eval(my_string)])
last_item = " ".join([str(k[-1]) for k in ast.literal_eval(my_string)])

更新

在您的问题中, my_string = '[[4.6, 4.3, 4.3, 85.05], [8.75, 5.6, 6.6, 441.0] [4.6, 4.3, 4.3, 85.9625]]' 如果您打算将其用作my_string ,请尝试以下操作:

my_string = " ".join(["x".join([str(k) for k in i[:-1]]) for i in [i.replace(",","").split() for i in my_string.replace("[","").split("]") if len(i) >1]])
last_item = " ".join([str(k[-1]) for k in [i.replace(",","").split() for i in my_string.replace("[","").split("]") if len(i) >1

在第二种情况下,我们首先执行my_string.replace("[","") ,结果为'4.6, 4.3, 4.3, 85.05], 8.75, 5.6, 6.6, 441.0] 4.6, 4.3, 4.3, 85.9625]]' 现在我们用.split("]")将它们分割成['4.6, 4.3, 4.3, 85.05', ', 8.75, 5.6, 6.6, 441.0', ' 4.6, 4.3, 4.3, 85.9625', '', ''] 我们需要删除这里只是空字符串的项目,因此if len(i) >1部分包含在列表if len(i) >1 ,我们if len(i) >1其合并。 现在我们得到['4.6, 4.3, 4.3, 85.05', ', 8.75, 5.6, 6.6, 441.0', ' 4.6, 4.3, 4.3, 85.9625'] 我们需要删除列表的字符串项中的逗号。 因此,对于此列表中的每个项目,我们都执行.replace(",","") ,然后执行.split() ,这将导致[['4.6', '4.3', '4.3', '85.05'], ['8.75', '5.6', '6.6', '441.0'], ['4.6', '4.3', '4.3', '85.9625']] 现在,对于每个子列表,我们将项目取到最后一个项目,然后执行"x".join()并分配给my_string 在该列表中,我们可以添加所有带有" ".join()的最后一项,并将其分配给last_item变量。

尝试使用dict

my_string = '[[4.6, 4.3, 4.3, 85.05], [8.75, 5.6, 6.6, 441.0], [4.6, 4.3, 4.3,` 85.9625]]'

    b = {'[': '', ']': '', ',': 'x'}
    for x, y in b.items():
        my_string = my_string.replace(x, y)
    print(my_string)

您的字符串看起来像有效的json字符串。 可能是这样的:

import json
def to_str(lst):
    return 'x'.join([str(e) for e in lst])
my_string = '[[4.6, 4.3, 4.3, 85.05], [8.75, 5.6, 6.6, 441.0], [4.6, 4.3, 4.3, 85.9625]]'
temp = json.loads(my_string)
first_items = ' '.join([to_str(x[:-1]) for x in temp])
last_items = ' '.join([str(x[-1]) for x in temp])
print(first_items)
print(last_items)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM