Reputation: 2495
I want to replace 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]]'
such that it gives result like this
my_string = '4.6x4.3x4.3 8.75x5.6x6.6 4.6x4.3x4.3'
last_item = '85.05 441.0 85.9625'
The last items in the list has no fixed length For the first objective I've written
mystring = mystring.replace("[","").replace("]","").replace(", ","x")
But I need a more pythonic way.
Upvotes: 1
Views: 96
Reputation: 2228
Your string looks like valid json string. Maybe like this:
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)
Upvotes: 0
Reputation: 6935
Try this if 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)])
UPDATE :
In your question, 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]]'
. If you intend to use this as my_string
, then try this :
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
In the second case, we first do my_string.replace("[","")
which results in '4.6, 4.3, 4.3, 85.05], 8.75, 5.6, 6.6, 441.0] 4.6, 4.3, 4.3, 85.9625]]'
. Now we split them with .split("]")
which results into ['4.6, 4.3, 4.3, 85.05', ', 8.75, 5.6, 6.6, 441.0', ' 4.6, 4.3, 4.3, 85.9625', '', '']
. We need to remove the items here which are just vacant string, so we incorporate if len(i) >1
part in the list comprehension. Now we get ['4.6, 4.3, 4.3, 85.05', ', 8.75, 5.6, 6.6, 441.0', ' 4.6, 4.3, 4.3, 85.9625']
. We need to remove the commas in the string items of the list. So for each item in this list we do .replace(",","")
and then followed by .split()
which now results in [['4.6', '4.3', '4.3', '85.05'], ['8.75', '5.6', '6.6', '441.0'], ['4.6', '4.3', '4.3', '85.9625']]
. Now for each sublist, we take items upto the last one and we do "x".join()
and assign to my_string
. Taking that list we can add all the last items with " ".join()
and assign that to last_item
variable.
Upvotes: 4
Reputation: 1334
Try using 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)
Upvotes: 0