Reputation: 360
I need to remove Square brackets and Double quotes from python list for further processing of data.
My code for the same is as follows:
ips = ['1.2.3.5','1.2.3.4']
y = []
for ip in ips:
x = "model.data.like('%"+ip+"%'),"
y.append([x])
print y
So here final result which I got is as follows:
["model.data.like('%1.2.3.5%'),"], ["model.data.like('%1.2.3.4%'),"]
Now here I need to get rid of square brackets and double quotes.
I need the output as follows:
model.data.like('%1.2.3.5%'),model.data.like('%1.2.3.4%')
Please have a note that IP address is dynamic one, List can contain more than two IP addresses.
Upvotes: 3
Views: 2140
Reputation: 5606
So, you do want to make a string from list? That's simple, you can use str.join
to do this:
ips = ['1.2.3.5','1.2.3.4']
# this is list comprehension, it does the same thing as your loop
y = ["model.data.like('%"+ip+"%')" for ip in ips]
print ','.join(y)
Upvotes: 1
Reputation: 5292
Use flattening list
and join
function-
>>>t=[item for sublist in y for item in sublist]
>>print t
>>>["model.data.like('%1.2.3.5%'),", "model.data.like('%1.2.3.4%'),"]
>>>data = ''.join(t)
>>>print data
>>>model.data.like('%1.2.3.5%'),model.data.like('%1.2.3.4%'),
>>>cleaned_data = data.rstrip(',')
>>>print cleaned_data
>>>model.data.like('%1.2.3.5%'),model.data.like('%1.2.3.4%')
Upvotes: 3
Reputation: 5061
You can use formatting the string by accessing the element of list
.
In [58]: s = ''
In [59]: for i in ips:
s = s + "model.data.like (%{}%),".format(i)
In [72]: s[:-1]
Out[72]: 'model.data.like (%1.2.3.5%),model.data.like (%1.2.3.4%)'
Upvotes: 1