How to remove newline characters in python?

I am writing a vcf parser and I have a file open, but now I need to parse their name. The file shows "FN: John Smith ;;; \ n \ r" I want to take out \ n and \ r. Can anybody help me?

+4
source share
2 answers

Use the rstrip function:

 s = s.rstrip() 

This will remove all spaces from the end of the line.

+12
source

If, as you say, the file shows "FN:John Smith;;;\n\r" , then you have a problem - that \r completely unexpected.

What operating system are you using, what version of Python, and exactly how did you determine that the file shows this?

Here is the usual idiom for reading a file with lines that end with the terminator commonly used by the OS you use, and has fields separated by characters ; :

 f = open('myfile.txt', 'r') for line in f: # standard OS terminator is converted to `\n` line = line.rstrip('\n') # remove trailing newline fields = line.split(';') # fields[0] should refer to "FN:John Smith" in your example for field_index, field in enumerate(fields): if not field: continue # empty field tag, value = field.split(':') print "Field %d: tag %r, value %r" % (field_index, tag, value) 

You may not have read this article . Wikipedia article ... I note that β€œFN” means β€œFormatted Name” and not β€œName”, and there is an β€œN” tag that will be easier to parse:

 N:Gump;Forrest FN:Forrest Gump 

I also note that a line similar to FN:John Smith;;; is not displayed in the article.

You may be able to use the existing code; see fooobar.com/questions/864693 / ....

+1
source

All Articles