assigning multi-line strings to variables

geremy condra debatem1 at gmail.com
Tue Apr 27 23:06:33 EDT 2010


On Tue, Apr 27, 2010 at 10:51 PM, goldtech <goldtech at worldpost.com> wrote:
> On Apr 27, 7:33 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
>> goldtech 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
>>
>> Use a triple-quoted string literal:
>>
>>  >>> d = """ddddd
>> ... ddddd"""
>>  >>> d
>> 'ddddd\nddddd'
>
> Only seems to work when there's a '... ' on the 2nd line. I need a way
> to assign large blocks of text to a variable w/out special formatting.
> Thanks.

The '...' is the interpreter's way of telling you that you are in a
block, e.g. a function definition, with statement, etc.

The '\n' you see in the middle of the string is the newline
character. If you try to print the string, the expected
happens:

>>> d = """dddddddddddddddd
... ddddddddddddddddddddddd"""
>>> d
'dddddddddddddddd\nddddddddddddddddddddddd'
>>> print(d)
dddddddddddddddd
ddddddddddddddddddddddd

Geremy Condra



More information about the Python-list mailing list