Python 删除每行中的字符串

Python 删除每行中的字符串,python,Python,我有以下输入字符串: omarReturn waelReturn 我希望输出字符串为: omar wael 这是我的密码 write = file("e", 'a') write.write(event.Key) if event.Key=="Return": read = file("e", 'r') lines = read.readlines() read.close() # How do I remo

我有以下输入字符串:

omarReturn
waelReturn
我希望输出字符串为:

omar
wael
这是我的密码

 write = file("e", 'a')
    write.write(event.Key)

    if event.Key=="Return":
        read = file("e", 'r')
        lines = read.readlines()
        read.close()
        # How do I remove "Return" from the lines
        write.write("\n")

这将删除字符串a中的每个返回

所以,迭代到每一行并在更改变量时使用此命令应该是可行的

a=a.replace("Return","")
你可以用。如果返回子字符串出现在末尾,这将删除它,否则不会删除

让我们制作一个函数子串移除器

输出:

omar
omarNormal
omarReturnExtra
因此,准确的代码将是:

with open('your_file','rw') as f:
    print '\n'.join([substring_remover(line) for line in f.read().splitlines()])  
    f.seek(0)
    f.write(value)
    f.truncate()

假设输入数据位于与Python代码相同的文件夹中名为“inputfile.txt”的文件中,并且以UTF-8编码

# Open the input file for reading.
with open('inputfile.txt', mode='r', encoding='utf-8') as infile:
    # Store all the data from the input file in a variable named
    #  'inlines'.  This only makes sense if you have a small amount
    #  of data, as you suggest you do.
    inlines = infile.readlines()

# Open or create a file named 'outputfile.txt' in the same folder as
#  'inputfile.txt' with UTF-8 encoding.
with open('outputfile.txt', mode='w', encoding='utf-8') as outfile:
    # Walk each line in the input file.
    for line in inlines:
        # Write each input line to the output file with 'Return'
        #  removed.
        outfile.write(line.replace('Return', ''))

这个stackoverflow问题可能很有用,您想删除任何“Return”还是只删除行末尾的Return
# Open the input file for reading.
with open('inputfile.txt', mode='r', encoding='utf-8') as infile:
    # Store all the data from the input file in a variable named
    #  'inlines'.  This only makes sense if you have a small amount
    #  of data, as you suggest you do.
    inlines = infile.readlines()

# Open or create a file named 'outputfile.txt' in the same folder as
#  'inputfile.txt' with UTF-8 encoding.
with open('outputfile.txt', mode='w', encoding='utf-8') as outfile:
    # Walk each line in the input file.
    for line in inlines:
        # Write each input line to the output file with 'Return'
        #  removed.
        outfile.write(line.replace('Return', ''))