[英]How to remove special character in a list of string and split it into separate elements
I have a list of string like this:我有一个像这样的字符串列表:
list = ["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]
Output expected shoud be:预期输出应该是:
list = ["A", "B", "C", "E", "0,2344", "0,234", "0,2345", "0,265", "0.2235"]
Can anyone suggest me some ways to do this?谁能建议我一些方法来做到这一点?
From what I understood from the comment.从我从评论中了解到的。 You can try this.你可以试试这个。
list_a=[j.strip() for i in list_a for j in i.split('|')]
Unrelated to the question: Don't use built-in / keywords name as variable names.与问题无关:不要使用内置 / 关键字名称作为变量名称。
you need:你需要:
new_list = []
for l in list1:
y = l.split("|")
new_list.extend([j.strip() for j in y if j])
print(new_list)
Output:输出:
['A', 'B', 'C', 'E', '0,2344', '0,234', '0,2345', '0,265', '0.2235']
You could do something like this,你可以做这样的事情,
lst = ["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]
output = []
for item in lst:
if item.find("|"):
values = item.replace("|", "").strip().split()
for value in values:
output.append(value.strip())
else:
output.append(item)
print(output)
Or better you could use list comprehension like this,或者更好的是你可以像这样使用列表理解,
lst =[subitem.strip() for item in lst for subitem in item.split('|') if subitem]
print(lst)
And output will be,输出将是,
['A', 'B', 'C', 'E', '0,2344', '0,234', '0,2345', '0,265', '0.2235']
hope this helps!希望这可以帮助!
ans= ''.join(i for i in '["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]'. replace('|','","'));
ans= ''.join(i for i in ans. replace(',""',''))
print(ans.replace(' ',''))
above code gives expected output as written below.上面的代码给出了预期的输出,如下所示。
["A","B","C","E","0,2344","0,234","0,2345","0,265","0.2235"]
Please do as follows:请按以下步骤操作:
list = ["A", "B", "C", "E", "0,2344 | 0,234 | 0,2345 | 0,265 | 0.2235 |"]
new_list = new_list = [ch.strip() for word in list for ch in word.split('|')]
new_list.remove('')
Thanks谢谢
I want to remove | character in the last element of list 1 and split last element of list 1 into last 5 elements of list 2
尝试这个
result = list[0:-1]+list[-1].replace(' ', '').strip('|').split('|')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.