[英]Removing Square Brackets and Double quotes from list
I need to remove Square brackets and Double quotes from python list for further processing of data. 我需要从python列表中删除方括号和双引号,以便进一步处理数据。
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. 请注意,IP地址是动态IP地址,列表可以包含两个以上IP地址。
Use flattening list
and join
function- 使用展flattening list
并join
功能-
>>>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%')
You can use formatting the string by accessing the element of list
. 您可以通过访问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%)'
So, you do want to make a string from list? 因此,您确实想从列表中创建一个字符串吗? That's simple, you can use str.join
to do this: 很简单,您可以使用str.join
来做到这一点:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.