Wednesday, April 18, 2012

Formatting line breaks in python strings

I have a string:



f = open("file.txt", r)
message = f.read()

print message
>>> "To: email\ntitle: add title here\nDescription: whatever here\n"


I can split the string by doing:



f_email, f_title, f_description, blank = message.split('\n')


But the problem arises when I have the message like this:



"To: email\ntitle: add title here\nDescription: first line\nSecond line\nthirdline\n"


When I split the string it splits the description as well. I have tried:



f_email, f_title, f_description, blank = message.split('\n',4)


But that obviously returns ValueError because it is splitting more 4 \n's.



Any suggestions?





No comments:

Post a Comment