assigning multi-line strings to variables

Lie Ryan lie.1296 at gmail.com
Wed Apr 28 12:54:53 EDT 2010


On 04/28/10 15:34, Alf P. Steinbach wrote:
> On 28.04.2010 07:11, * Sagar K:
>> Use triple quote:
>> d = """ this is
>> a sample text
>> which does
>> not mean
>> anything"""
>>
>> "goldtech"<goldtech at worldpost.com>  wrote in message
>> news:4e25733e-eafa-477b-a84d-a64d139f7134 at u34g2000yqu.googlegroups.com...
>> On Apr 27, 7:31 pm, Brendan Abel<007bren... at gmail.com>  wrote:
>>> On Apr 27, 7:20 pm, goldtech<goldt... at worldpost.com>  wrote:
>>>
>>>> Hi,
>>>
>>>> This is undoubtedly a newbie question. How doI assign variables
>>>> multiline strings? If I try this i get what's cited below. Thanks.
>>>
>>>>>>> d="ddddd
>>>> ddddd"
>>>>>>> d
>>>
>>>> Traceback (most recent call last):
>>>> File "<interactive input>", line 1, in<module>
>>>> NameError: name 'd' is not defined
>>>
>>> d = "ddddddddd"\
>>> "ddddd"
>>>
>>> or
>>>
>>> d = "dddddddddd\
>>> dddddd"
>>>
>>> You don't need the trailing slash in the first example if you are
>>> writing this in a script, python assumes it.
>>
>> Thanks but what if the string is 500 lines. Seems it would be hard to
>> put a "\" manually at the end of every line. How could i do that?
> 
> That depends. You can put the string in a separate text file and read
> the file, or you can have it as a literal. For the latter your editor
> should provide you with the tools to format the string any which way you
> want, and if not, then just a write a Python script to format it for you.
> 
> Consider this little example[1]:
<snip>

Python have triple-quoted string when you want to include large amount
of text; there is no need to split the string up manually or even
scriptically.

d = """
’Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

“Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!”

He took his vorpal sword in hand:
Long time the manxome foe he sought—
So rested he by the Tumtum tree,
And stood awhile in thought.

And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One, two! One, two! and through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

“And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!”
He chortled in his joy.

’Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
"""

I copied that in less then 10 seconds.



More information about the Python-list mailing list