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

后端 未结 8 1172
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 22:13

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.         


        
相关标签:
8条回答
  • 2021-02-06 22:35

    Here is another way :

    In [6]: line = "foo;bar"
    In [7]: line[:line.find(";")] + "\n"
    Out[7]: 'foo\n'
    
    0 讨论(0)
  • 2021-02-06 22:41

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

    rtr = line.partition(';')[0].rstrip() + '\n'
    
    0 讨论(0)
  • 2021-02-06 22:44
    file = open(r'c:\temp\test.txt', 'r')
    for line in file:   print
       line.split(";")[0].strip()
    
    0 讨论(0)
  • 2021-02-06 22:45

    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:

    • split
    • rstrip
    0 讨论(0)
  • 2021-02-06 22:46

    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'))
    
    0 讨论(0)
  • 2021-02-06 22:54

    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.

    0 讨论(0)
提交回复
热议问题