在Python 2.4中,如何在';'之后删除字符?

时间:2009-07-24 15:15:17

标签: python string python-2.4

假设我正在解析一个文件,该文件使用;作为注释字符。我不想解析评论。所以如果我的一行看起来像这样:

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'

8 个答案:

答案 0 :(得分:101)

我建议说

line.split(";")[0]

将为您提供所有字符的字符串,但不包括第一个“;”字符。如果不 ”;”字符存在,然后它会给你整行。

答案 1 :(得分:15)

只需通过注释对该行进行拆分,然后获取第一个元素 例如

line.split(";")[0]

答案 2 :(得分:4)

对于Python 2.5或更高版本,我会使用partition方法:

rtr = line.partition(';')[0].rstrip() + '\n'

答案 3 :(得分:3)

file = open(r'c:\temp\test.txt', 'r')
for line in file:   print
   line.split(";")[0].strip()

答案 4 :(得分:2)

因此,您需要在第一个分号上拆分该行,将所有内容分开,删除任何延迟的空格,然后附加换行符。

rtr = line.split(";", 1)[0].rstrip() + '\n'

指向文档的链接:

答案 5 :(得分:1)

在一行python中读取,拆分,剥离和连接换行符:

rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r'))

答案 6 :(得分:0)

这是另一种方式:

In [6]: line = "foo;bar"
In [7]: line[:line.find(";")] + "\n"
Out[7]: 'foo\n'

答案 7 :(得分:-2)

我没有用python测试过这个,但我在其他地方使用了类似的代码。

import re
content = open(r'c:\temp\test.txt', 'r').read()
content = re.sub(";.+", "\n")
相关问题