删除每个lin中的字符串

2024-03-29 16:01:42 发布

您现在位置: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 remove "Return" from the lines
        write.write("\n")

Tags: key字符串event密码readreturniffile
3条回答

假设输入数据位于名为'输入文件.txt'在与Python代码相同的文件夹中,并且它是用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', ''))

这将从字符串“a”中删除每个“Return”。你知道吗

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

a=a.replace("Return","")

您可以使用re.sub()。如果"Return"子字符串出现在末尾,则会删除它,否则不会。你知道吗

让我们做一个函数substring_remover()

import re 
def substring_remover(whole_string):
    return re.sub(r'(.+)(Return)$',r'\1',whole_string)      

print substring_remover('omarReturn') # Will remove "Return" as it is at the end
print substring_remover('omarNormal') # Will remove nothing as there is no "Return"
print substring_remover('omarReturnExtra') # Will remove nothing because "Return" exists but not at the end. 

输出:

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()

相关问题 更多 >