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?
When you run
.split('\n')you return a list. Rather than assign the variables when you split, you can pull them out of the list:This can be made less fragile by checking the size of the list. If you know it needs at least three elements, you can:
Another way to get around this is to wrap the thing up in a
try/exceptblock:That way you can handle the case for a shorter list the exact way you like!