In Python 2.4, how can I strip out characters after ';'?

狂风中的少年 提交于 2019-12-03 09:23:08

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.

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

line.split(";")[0]

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

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

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:

Reading, splitting, stripping, and joining lines with newline all in one line of python:

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!