How to write multiple rows in Python?

8

How can I write a string with multiple lines in Python?

As I come from PHP, I usually do this:

$string = "
uma linha
outra linha2
"

Or:

$string = <<<EOT
uma linha
outra linha
EOT;

When I try to do this in Python, it generates an error.

Example:

string = '
uma linha
outra linha
'

Result:

  

EOL while scanning string literal

How can I do this in Python?

    
asked by anonymous 13.08.2015 / 14:47

3 answers

10

Triple quotes:

print("""linha1
linha2
linha3
""")

See working on ideone .

You can use single quotation marks as long as they are triplicated.

But you can not use indentation under penalty of being string .

See running on ideone .

This can also be used as doc strings . That are nothing else than strings loose in the code. They will not be assigned to the variables nor will they be printed, they will only be part of the code and this indicates that it is a comment of documentation that later can be read by some specific tool.

    
13.08.2015 / 14:57
4

To make a string have multiple lines you can use the% wrap character \n . So:

string = 'uma linha\noutra linha'
print string

You can still use the os.linesep function which according to the documentation it makes use of the most appropriate line break character for your operating system, in case Windows would be \r\n .

string = 'uma linha%soutra linha' % os.linesep
print string

Result for any of the above two cases:

  

one line
  other line

See working on Ideone .

Reference: Python Docs - linesep .

If you need to use several lines to form a string with a line you can do with \ :

string = '\
uma linha \
outra linha\
'
print string

Or with () :

string = ('uma linha '
'outra linha')
print string

Or even with () and + .

string = ('uma linha ' +
'outra linha')
print string

Result for any of the above three cases:

  

one line another line

See working on Ideone .

    
13.08.2015 / 14:54
0

And if you want to print variable values on these lines, you can do this:

Remembering that I'm using Python 3.5

nome = 'rafael'
idade = '21'
peso = '68'
altura = '1.70'

print (
'\nNome: ' + nome +
'\nIdade: ' + idade +
'\nPeso: ' + peso+
'\nAltura: ' + altura +
'\n'
)
    
05.01.2017 / 23:49