首页 > 解决方案 > 从列表项的末尾删除 \n

问题描述

我有这个代码

def return_not_existing_signals(list_of_signals,read_or_write) :
    not_used_produced_signals = []
    #print(list_of_signals)
    if read_or_write =="read":
        file_to_create= "c:\\path\\read.txt"
    else:
        file_to_create = "c:\\path\\write.txt"

    for i in list_of_signals :
        i.replace('\n','')
        if not search_for_signals(i) :
            not_used_produced_signals.append(i)
    write_to_txt(not_used_produced_signals,file_to_create)


def search_for_signals(name_of_signal):
    for filename in Path('c:\path').glob('**/*.h') : 
        with open(filename) as f:
            if name_of_signal in f.read():
                return True
    return False

问题是其中一些list_of_signals在末尾有\n(例如:test1234rwq4\n)

I.replace(\'n',' ' )不工作

标签: python

解决方案


来自文档

string.replace(s, old, new[, maxreplace])

返回字符串 s 的副本, 其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 maxreplace,则替换第一个 maxreplace 出现。

因此,您需要将其视为,

i = i.replace('\n','')

推荐阅读