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

标签 python python-3.x string replace formatting

我想替换我的字符串

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 部分合并到列表推导中。现在我们得到 ['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 变量。

关于python - 替换和删除字符串中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55040539/

相关文章:

python - Cv2 :problem recieving full data from socket

JavaScript 拆分,更改零件编号

Python 3.x 舍入行为

python - scipy linregress : computing only scaling/slope parameter with intercept fixed at 0

python - 连接两个列表中相同索引处的字符串

python - 如何在 Flask 中存储 Session 的用户数据?

python - 如何在 python 3.x 中使用字符串创建 if 语句

python - 仅当位置可被给定值整除时,才使用 matplotlib.ticker.Locator 放置刻度

c++ - 对其中包含数字的字符串进行排序

在 C 中将指针转换回数组