Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a single backslash?

When I write print('\') or print("\") or print("'\'"), Python doesn't print the backslash \ symbol. Instead it errors for the first two and prints '' for the second. What should I do to print a backslash?

like image 344
Michael Avatar asked Sep 30 '13 13:09

Michael


People also ask

How do you print a backslash?

Program to Print Backslash () in C# \ is a special character (sign) In C#. It is used for escape sequences(break out) such as to print a new line – we use \n, to print a tab – we use \t. We have to use a double backslash (\\) to print a backslash (\).

How do you get a single backslash in Python?

The Python backslash ( '\' ) is a special character that's used for two purposes: The Python backslash can be part of a special character sequence such as the tab character '\t' , the newline character '\n' , or the carriage return '\r' .

What is the escape sequence to print one back slash character to the screen?

The backslash itself is an escape character so it must be escaped by itself to print just one backslash.

How do you string a backslash?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.


1 Answers

You need to escape your backslash by preceding it with, yes, another backslash:

print("\\") 

And for versions prior to Python 3:

print "\\" 

The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

See the Python 3 documentation for string literals.

like image 163
Bucket Avatar answered Oct 12 '22 23:10

Bucket