Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define __str__ in python when including newline characters?

I'm trying to define str() for a maze object and have it print out something that looks like this:

#######
#J..P.#
#.###.#
#..@#.#
#@#.@.#
#######

When I build the string to return, however, it ends up getting printed as:

'#######\n#J..P.#\n#.###.#\n#..@#.#\n#@#.@.#\n#######\n'

All I'm doing is going through the list of lists (each row is a list, and the whole maze is a list of these row lists) and concatenating a "\n" at the end of each row. Is there something else I'm supposed to do to the resulting string before returning it so that the string representation of the maze when print() or str() is called on it will return that first desired representation?

like image 794
sabliao Avatar asked Oct 27 '25 08:10

sabliao


1 Answers

Are you printing with the print statement, or just by letting Python print the value? Eg.:

>>> a = "This is a\nmultiline string"
>>> a
'This is a\nmultiline string'
>>> print a
This is a
multiline string

That's just normal Pythonic behaviour.

like image 98
rici Avatar answered Oct 29 '25 21:10

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!