To avoid a newline in multi-line strings

bearophile bearophileHUGS at lycos.com
Sat Jul 23 07:57:43 PDT 2011


After a short discussion in D.learn I have created a tiny enhancement request:
http://d.puremagic.com/issues/show_bug.cgi?id=6361

I show its text here too. It's not essential, it's a minor thing.

Multi-line strings are handy, but I have a small problem with them. This is an example, it has a problem, there is an unwanted newline at the beginning (the situation is the same if you use ` instead of "):

string table = "
- First item:  150
- Second item: 200
- Third item:  105";


(If you are just writing such string then you can use just write() followed by a flush.)


To avoid it you can write this, but both break the alignment in the source code, and they are not nice looking:

string table = "- First item:  150
- Second item: 200
- Third item:  105";


string table =
"- First item:  150
- Second item: 200
- Third item:  105";


This solution adds one ending newline instead:

    writeln(q"EOS
- First item:  150
- Second item: 200
- Third item:  105
EOS");



To solve that problem in Python you use this (in Python """ or ''' denote a multi-line string):

table = """\
- First item:  150
- Second item: 200
- Third item:  105"""


The extra slash at the beginning avoids the start newline.

I think it's worth adding this little Python syntax detail to D too.

-------------

Note: this syntax is not meant to solve the more general problem in presence of indentation. In this case you probably need a library solution to de-indent, etc:

void foo()
{
    if(blah)
    {
        writeln("- First item:  150
            - Second item: 200
                -- Subitem 1
                -- Subitem 2
            - Third item:  105");
    }
}


(Thanks to Nick Sabalausky and Andrej Mitrovic for the suggestions and comments.)

Bye,
bearophile


More information about the Digitalmars-d mailing list