String problem

Peter Hansen peter at engcorp.com
Sat May 25 23:03:18 EDT 2002


Occean wrote:
> 
> Assume that you have an text article.
[snip]
> you have to read the article into a string called str [snip]  
> The problem is when you read the article in the string
> you have to put "\n\" at the end of each line in order to let the system
> know the new line. For example:
> str = ' Paint my love, you should paint my love\n\
>           It's a picture of thousand sunset \n\
>           \n\
>           It's a freedom of , a thousand doves\n\'

Your question is unclear.  When you "read the article into a string"
do you mean you are reading it from a file?  In that case, the
newlines ('\n') should already be on the end of each line.

Do you mean you are creating the string statically in the program
itself, sort of as in your example?  In that case, use the triple-quoted
string syntax (after all, you're example above won't work 
anyway since you have an apostrophe in the middle):

str = '''Paint my love, you should paint my love
It's a picture of a thousand sunset

It's a freedom of, a thousand doves
'''

That string will include the newlines as well.

Another alternative is this:

str = ["Paint my love, you should paint my love",
       "It's a picture of a thousand sunset",
       "",
       "It's a freedom of, a thousand doves",
      ]
str = '\n'.join(str) + '\n'

(or, on Python 1.5.2, use str = string.join(str, '\n') + '\n' )

I've added the extra '\n' at the end because your example
had it, but you probably don't really need it.

-Peter
How about i have to write the program to allow user input something and
then read the input text into my function in order to save into the file
exactly the same what the user typed . For example, 
"Dear John,

I am so glad to see you .....
....

Best Regard
John."

I tried to work with triple quote """ but it didn't same to help me
caused i always missed some line.. I don't want to put ( " " ) or (\n\)
in anyline.



More information about the Python-list mailing list