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'
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.
只是通过注释在行上拆分,然后获取第一个元素,例如
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的一行来读取,拆分,剥离和使用newline合并行:
rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r'))
Here is another way :
In [6]: line = "foo;bar" In [7]: line[:line.find(";")] + "\n" Out[7]: 'foo\n'
I have not tested this with python but I use similar code else where.
import re
content = open(r'c:\temp\test.txt', 'r').read()
content = re.sub(";.+", "\n")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.