如何替换“ |”与''或空字符串?

时间:2019-05-25 10:33:09

标签: python

我从数据中删除了所有空值和数字。我只有包含文本字符串和'|'的列表的列表。我想遍历我的RDD对象并替换'|'加上”,甚至将其删除。

我尝试使用map函数,然后将其链接到外部函数

def fun(item):
    newlist=list()
    for i in item:
        if '|' == i or '|' in i:
            j=''
            newlist.append(j)
        else:
            newlist.append(i)
    return newlist

final=orginial.map(x : fun(x))

input: [['Hello','|'],..]

expected output: [['Hello',''],..]

actual output: [['Hello','|'],..]

1 个答案:

答案 0 :(得分:0)

您可以在python中使用replace

a = "ABCD|EFG"
a = a.replace("|", "")

我更改您可以使用的代码:

def fun(item):
    newlist=list()
    for i in item:
        newlist.append(i.replace("|",""))
    return newlist

如果您想摆脱空字符串,也可以尝试

output = []

for single_list in list_of_lists:
    new_in_list = [i for i in single_list if not i is "|"]
    output.append(new_in_list)

我添加更多示例:

a = ["hello|||", "he||oagain", "|this is |", "how many ||||||||| ?"]
output = []
for i in a:
    output.append(i.replace("|", ""))
print(output)

最后的输出是:

['hello', 'heoagain', 'this is ', 'how many  ?']
相关问题