Skip to content Skip to sidebar Skip to footer

Is There A Clean Way To Write Multi-lines Strings In Python?

It sounds like a beginner question, but I never succeeded in writing long strings in a clean way in Python. Here are the 4 ways I listed to do it. None of them seems ok to me. def

Solution 1:

I would go with:

def pr():
    # parentheses are for grouping and (as a bonus) for a pretty indentation
    s = ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa""bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
    print s

To quote an informal introduction to Python:

Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions.

>>>s = 'a''b'>>>s
'ab'
>>>s = 'a''b'# space is not necessary>>>s
'ab'

A side note: the concatenation is performed during the compilation to bytecode:

>>>import dis>>>dis.dis(pr)

 0 LOAD_CONST               1 ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

Probably this concatenation tradition comes from C:

// prints "hello world"#include<stdio.h>intmain(int argc, char **argv){
  printf("hello"" world");
  return0;
}

Solution 2:

You can try:

string = "sdfsdfsdfsdfsdf" \
         "sdfsdfsdfsdfs"

And the result:

>>> string'sdfsdfsdfsdfsdfsdfsdfsdfsdfs'

The same effect can be achieved by using paranthesis instead of \, as @Nigel Tufnel mentioned in his answer.

Solution 3:

What about using double or single triple quote:

>>>string_A = """Lorem ipsum dolor sit amet,...this is also my content...this is also my content...this is also my content""">>>>>>print string_A
Lorem ipsum dolor sit amet,
this is also my content
this is also my content
this is also my content
>>>

Solution 4:

I think it boils down to how much screen real-estate you are afforded.

You could use concatenation..

string_a = "this is my content"
string_a += "this is also my content"

Post a Comment for "Is There A Clean Way To Write Multi-lines Strings In Python?"