Trindaz
Trindaz

Reputation: 17879

Printing unescaped white space to shell

Consider this line of Python code:

s = "This string has \n\r whitespace"

How do I make

print s

give me

This string has \n\r whitespace

instead of

This string has
whitespace

as it does now.

Upvotes: 13

Views: 16099

Answers (4)

andronikus
andronikus

Reputation: 4220

You can use python's formatting capabilities to print the string in its "raw" form:

print "%r" % s

You can also create a string in raw form like this:

s = r'This string has \n\r whitespace'

and Python will handle escaping the backslashes so that that is exactly what you get:

print s # outputs "This string has \n\r whitespace"

Upvotes: 1

Wooble
Wooble

Reputation: 90007

 print s.encode('string-escape')

Upvotes: 9

Michał Šrajer
Michał Šrajer

Reputation: 31182

do you want a raw string ?

s = r"This string has \n\r whitespace"

or to transform special characters to it's representation?

repr(s)

Upvotes: 27

g.d.d.c
g.d.d.c

Reputation: 48028

You want the repr function.

print repr(s)

Upvotes: 4

Related Questions