assigning multi-line strings to variables

G

goldtech

Hi,

This is undoubtedly a newbie question. How doI assign variables
multiline strings? If I try this i get what's cited below. Thanks.

Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'd' is not defined
 
B

Brendan Abel

Hi,

This is undoubtedly a newbie question. How doI assign variables
multiline strings? If I try this i get what's cited below. Thanks.


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.
 
M

MRAB

goldtech said:
Hi,

This is undoubtedly a newbie question. How doI assign variables
multiline strings? If I try this i get what's cited below. Thanks.


Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'd' is not defined

Use a triple-quoted string literal:
'ddddd\nddddd'
 
G

goldtech

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?
 
G

goldtech

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.
 
M

MRAB

goldtech said:
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.

I copied it from an interactive session in IDLE. In an actual script I
would write:

text = """first line
second line
third line"""
 
S

Sagar K

Use triple quote:
d = """ this is
a sample text
which does
not mean
anything"""

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?
 
A

Alf P. Steinbach

Use triple quote:
d = """ this is
a sample text
which does
not mean
anything"""



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]:


<code file="jabberwocky.py">
"The Jabberwocky poem, by Lewis Carrol"

text = (
"'Twas brillig, and the slithy toves\n"
"Did gyre and gimble in the wabe;\n"
" All mimsy were the borogoves,\n"
" And the mome raths outgrabe.\n"
"\n"
"\"Beware the jabberwock, my son!\n"
" The jaws that bite, the claws that catch!\n"
"Beware the jubjub bird, and shun\n"
" The frumious bandersnatch!\"\n"
"\n"
"He took his vorpal sword in hand:\n"
" Long time the manxome foe he sought--\n"
"So rested he by the tumtum tree,\n"
" And stood awhile in thought.\n"
"\n"
"And as in uffish thought he stood,\n"
" The jabberwock, with eyes of flame,\n"
"Came whiffling through the tulgey wood,\n"
" And burbled as it came!\n"
"\n"
"One, two! one, two! and through and through\n"
" The vorpal blade went snicker-snack!\n"
"He left it dead, and with its head\n"
" He went galumphing back.\n"
"\n"
"\"And hast thou slain the jabberwock?\n"
" Come to my arms, my beamish boy!\n"
"O frabjous day! callooh! callay!\"\n"
" He chortled in his joy.\n"
"\n"
"'Twas brillig, and the slithy toves\n"
"Did gyre and gimble in the wabe;\n"
" All mimsy were the borogoves,\n"
" And the mome raths outgrabe."
)
</code>


This defines /one/ string value, using compile time concatenation (any adjacent
string literals are concatenated at compile time, in Python[2] and in C++).

The text was just copied and pasted from Wikipedia, and subjected to a few well
chosen keystrokes in an editor.

As a hopefully illuminating exercise, consider a Python program that uses this
string (just import the above module and use its 'text') and generates the above
source code as output.


Cheers & hth.,

- Alf

Notes:
[1] From an example at the end of chapter 2 at <url:
http://tinyurl.com/programmingbookP3>.
[2] I'm not sure how well that plays with Python doc strings; haven't tried.
 
C

cjw

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.
What about:
*** Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit
(Intel)] on win32. ***.... all good men
.... to come to the aid
.... of the party''' Now is the time for
all good men
to come to the aid
of the party
Colin W.
 
L

Lie Ryan

Use triple quote:
d = """ this is
a sample text
which does
not mean
anything"""



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.
 
A

Alf P. Steinbach

Use triple quote:
d = """ this is
a sample text
which does
not mean
anything"""


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;

Yes, that's been mentioned umpteen times in this thread, including the *very
first* quoted sentence above.

It's IMHO sort of needless to repeat that after quoting it, and providing yet
another example right after quoting an example.

Probably you didn't notice?

there is no need to split the string up manually or even
scriptically.

Consider that the concatenation language feature probably is there because it's
useful (e.g. it preserves indentation and allows per line comments).

d = """
’Twas brillig, and the slithy toves

Here you have introduced an unintentional linebreak, oops.

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.

Doesn't matter how fast it is when it's not correct (or, from another point of
view, if it doesn't need to be done correctly then it can be arbitrarily fast).

Of course you can fix it, but since you posted it with errors I think you were
not aware.

In the end there are drawbacks to any way of doing it, so it's to a large degree
a matter of personal preference, as I see it. I just mentioned two additional
ways not yet discussed in the thread. Exemplifying one of them.


Cheers,

- Alf
 
L

Lie Ryan

Yes, that's been mentioned umpteen times in this thread, including the
*very first* quoted sentence above.

It's IMHO sort of needless to repeat that after quoting it, and
providing yet another example right after quoting an example.

Probably you didn't notice?

I do, my complaints is that you're making it needlessly complex.
Consider that the concatenation language feature probably is there
because it's useful (e.g. it preserves indentation and allows per line
comments).

No, the implicit concatenation is there because Python didn't always
have triple quoted string. Nowadays it's an artifact and triple quoted
string is much preferred. Long dump of text in source code is usually
(or should be) globals constant anyway and you have no problem about
indentation in globals constant. The only ubiquitous place where you
need to put long stream of triple-quoted in non-global is as docstring;
and docstring already handles the problem with indentation.
Doesn't matter how fast it is when it's not correct (or, from another
point of view, if it doesn't need to be done correctly then it can be
arbitrarily fast).

It's the nature of the text, who cares about extra line breaks or two.
If this string has been for regex, I'd probably care.
Of course you can fix it, but since you posted it with errors I think
you were not aware.

I used triple-quote a lot, and I'm very aware of that.
In the end there are drawbacks to any way of doing it, so it's to a
large degree a matter of personal preference, as I see it. I just
mentioned two additional ways not yet discussed in the thread.
Exemplifying one of them.

When you have long stream of text and you paste it in source code, it's
usually for one-off scripts that you're too lazy to create a proper file
to read from. You never want to have to do some tedious preprocessing
before you can insert it to the source.

There's never a good reason to insert very long streams of text using
implicit concatenation; not since docstring is here.
 
S

Steven D'Aprano


Yes, it says:

* String literals follow Standard C rules: they may be continued
on the next line using a backslash; adjacent literals are
concatenated at compile time.

* A new kind of string literals, surrounded by triple quotes
(""" or '''), can be continued on the next line without a
backslash.


These are adjacent entries in the same release. That's pretty good
evidence that both implicit concatenation and triple quotes were
introduced at the same time.
 
G

Gregory Ewing

Lie said:
No, the implicit concatenation is there because Python didn't always
have triple quoted string. Nowadays it's an artifact and triple quoted
string is much preferred.

I don't agree. I often use implicit concatenation when I'm
writing a format string that won't fit on one source line,
because it allows me to fit it into the surrounding indentation
structure without introducing unwanted spaces into the string.

Both tecnhiques have their places.
 
G

goldtech

Thank you to posters for help to my question. Seems I had trouble with
triple quotes strings in the PythonWin shell. But using the Idle shell
things work as expected. But this is probably another issue...any way,
w/Idle's shell I got the "action" regarding multiline strings I
expected.
 
L

Lie Ryan

I don't agree. I often use implicit concatenation when I'm
writing a format string that won't fit on one source line,
because it allows me to fit it into the surrounding indentation
structure without introducing unwanted spaces into the string.

Both tecnhiques have their places.

That statement should be quantified with "for large chunks of text".
Format string is typically 2-3 lines at most, not enough to qualify as
large chunk.
 
L

Lie Ryan

Yes, it says:

* String literals follow Standard C rules: they may be continued
on the next line using a backslash; adjacent literals are
concatenated at compile time.

* A new kind of string literals, surrounded by triple quotes
(""" or '''), can be continued on the next line without a
backslash.


These are adjacent entries in the same release. That's pretty good
evidence that both implicit concatenation and triple quotes were
introduced at the same time.

Yes, apparently my statement that implicit concatenation is an artifact
is erroneous but it doesn't make the important points less true, that
implicit concatenation is not suitable for integrating large chunk of
text into source code.

And if you do care about the two extra newlines, you can add two
backslashes:

s = """\
....
insert large chunks
....\
"""

which is a constant-time preformatting compared to prepending and
appending every line with quotes, which is O(n) (and we're talking about
the oh-so-expensive programmer's time here).

Ben Finney also showed the trick to let a large chunk to appear indented
and stripping the indenting at runtime in another thread (which is
actually rarely needed since, since as I previously said, huge chunk of
text is usually global-level variable; though the trick does come handy
sometimes).
 
C

Carl Banks

On 28.04.2010 18:54, * Lie Ryan:

Yes, that's been mentioned umpteen times in this thread, including the *very
first* quoted sentence above.

It's IMHO sort of needless to repeat that after quoting it, and providing yet
another example right after quoting an example.

Probably you didn't notice?


I think he repeated it just to let people know that they can get what
they want without following your adsurd advice.


Carl Banks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top