In Python 2.4, how can I strip out characters afte

2019-03-22 14:56发布

Let's say I'm parsing a file, which uses ; as the comment character. I don't want to parse comments. So if I a line looks like this:

example.com.              600     IN      MX      8 s1b9.example.net ; hello!

Is there an easier/more-elegant way to strip chars out other than this:

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条回答
干净又极端
2楼-- · 2019-03-22 15:00

just do a split on the line by comment then get the first element eg

line.split(";")[0]
查看更多
爷、活的狠高调
3楼-- · 2019-03-22 15:03

I'd recommend saying

line.split(";")[0]

which will give you a string of all characters up to but not including the first ";" character. If no ";" character is present, then it will give you the entire line.

查看更多
欢心
4楼-- · 2019-03-22 15:04

For Python 2.5 or greater, I would use the partition method:

rtr = line.partition(';')[0].rstrip() + '\n'
查看更多
ゆ 、 Hurt°
5楼-- · 2019-03-22 15:08

Here is another way :

In [6]: line = "foo;bar"
In [7]: line[:line.find(";")] + "\n"
Out[7]: 'foo\n'
查看更多
何必那么认真
6楼-- · 2019-03-22 15:17

So you'll want to split the line on the first semicolon, take everything before it, strip off any lingering whitespace, and append a newline character.

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

Links to Documentation:

查看更多
干净又极端
7楼-- · 2019-03-22 15:23
file = open(r'c:\temp\test.txt', 'r')
for line in file:   print
   line.split(";")[0].strip()
查看更多
登录 后发表回答