Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' 
like image 500
lfaraone Avatar asked Jul 24 '09 15:07

lfaraone


People also ask

How do you strip a string after a character in Python?

To remove everything after the first occurrence of the character '-' in a string, pass the character '-' as separator and 1 as the max split value. The split('-', 1) function will split the string into 2 parts, Part 1 should contain all characters before the first occurrence of character '-'.

How do you remove unwanted characters from Python?

The most common way to remove a character from a string is with the replace() method, but we can also utilize the translate() method, and even replace one or more occurrences of a given character.

How do I remove all characters from a string after a specific character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .


2 Answers

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.

like image 120
Eli Courtwright Avatar answered Oct 06 '22 01:10

Eli Courtwright


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

line.split(";")[0] 
like image 27
ghostdog74 Avatar answered Oct 06 '22 01:10

ghostdog74