Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print escaped representation of a str

How do I print the escaped representation of a string, for example if I have:

s = "String:\tA"

I wish to output:

String:\tA

on the screen instead of

String:    A

The equivalent function in java is:

String xy = org.apache.commons.lang.StringEscapeUtils.escapeJava(yourString);
System.out.println(xy);

from Apache Commons Lang

like image 840
Baz Avatar asked Feb 19 '13 15:02

Baz


People also ask

How do you write a character escaped string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do I print a string without escape characters?

Solution 2: Print Raw String to Ignore Special Meaning of Escape Chars. Alternatively, you can print a raw string r"..." to print the string without interpreting the escape characters. For example, the statement print('r"Learn\tprogramming\nwith\t') will simply print the raw string "Learn\tprogramming\nwith\t" .

How do you print escape in Python?

To print a backslash to the console, we have to use the double backslashes ( \\ ). Let's try it. \n means a new line. We will get a new line when we use the escape sequence \n in the print function.

How do you print an escape character in Java?

A character with a backslash (\) just before it is an escape sequence or escape character.


2 Answers

You want to encode the string with the string_escape codec:

print s.encode('string_escape')

or you can use the repr() function, which will turn a string into it's python literal representation including the quotes:

print repr(s)

Demonstration:

>>> s = "String:\tA"
>>> print s.encode('string_escape')
String:\tA
>>> print repr(s)
'String:\tA'

In Python 3, you'd be looking for the unicode_escape codec instead:

print(s.encode('unicode_escape'))

which will print a bytes value. To turn that back into a unicode value, just decode from ASCII:

>>> s = "String:\tA"
>>> print(s.encode('unicode_escape'))
b'String:\\tA'
>>> print(s.encode('unicode_escape').decode('ASCII'))
String:\tA
like image 118
Martijn Pieters Avatar answered Sep 18 '22 06:09

Martijn Pieters


you can use repr:

print repr(s)

demo

>>> s = "String:\tA"
>>> print repr(s)
'String:\tA'

This will give the quotes -- but you can slice those off easily:

>>> print repr(s)[1:-1]
String:\tA
like image 24
mgilson Avatar answered Sep 21 '22 06:09

mgilson