在Python 2.4中,如何去掉“;”后面的字符?
-
19-09-2019 - |
题
假设我正在解析一个文件,它使用 ;
作为评论字符。我不想解析评论。所以如果我的一行看起来像这样:
example.com. 600 IN MX 8 s1b9.example.net ; hello!
除了这个之外,还有更简单/更优雅的方法来去除字符:
rtr = ''
for line in file:
trig = False
for char in line:
if not trig and char != ';':
rtr += char
else:
trig = True
if rtr[max(rtr)] != '\n':
rtr += '\n'
解决方案
我会建议说
line.split(";")[0]
,这将给你的所有字符直到但不包括所述第一的字符串“;”字符。如果不 ”;”字符存在,则它将给你整行。
其他提示
只是由注释的行分裂然后得到的第一个元素 例如
line.split(";")[0]
有关的Python 2.5或更大,我会使用 partition
方法:
rtr = line.partition(';')[0].rstrip() + '\n'
file = open(r'c:\temp\test.txt', 'r')
for line in file: print
line.split(";")[0].strip()
阅读,分裂,剥离,并且所有在python的一行与接合线换行符:
rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r'))
下面是另一种方式:
In [6]: line = "foo;bar" In [7]: line[:line.find(";")] + "\n" Out[7]: 'foo\n'
我还没有与Python测试这一点,但我其他使用类似的代码,其中
import re
content = open(r'c:\temp\test.txt', 'r').read()
content = re.sub(";.+", "\n")
不隶属于 StackOverflow