How to print "\" in python? - python

print "\\"
It print me in console...
But I want to get string \
How to get string string \?

There's clearly some sort of configuration with your console that's wrong. Doing this:
print "\\"
Clearly prints \ for me.

You can add letter r to string before quotes (r for raw). It will ignore all special symbols.
For example
>>> print '\x63\\ Hello \n\n8'
c\ Hello
8
>>> print r'\x63\\ Hello \n\n8'
\x63\\ Hello \n\n8
So printing backslash is print r'\'

Related

Printing Single Quote inside the string

I want to output
XYZ's "ABC"
I tried the following 3 statements in Python IDLE.
1st and 2nd statement output a \ before '.
3rd statement with print function doesn't output \ before '.
Being new to Python, I wanted to understand why \ is output before ' in the 1st and 2nd statements.
>>> "XYZ\'s \"ABC\""
'XYZ\'s "ABC"'
>>> "XYZ's \"ABC\""
'XYZ\'s "ABC"'
>>> print("XYZ\'s \"ABC\"")
XYZ's "ABC"
Here are my observations when you call repr() on a string: (It's the same in IDLE, REPL, etc)
If you print a string(a normal string without single or double quote) with repr() it adds a single quote around it. (note: when you hit enter on REPL the repr() gets called not __str__ which is called by print function.)
If the word has either ' or " : First, there is no backslash in the output. The output is gonna be surrounded by " if the word has ' and ' if the word has ".
If the word has both ' and ": The output is gonna be surrounded by single quote. The ' is gonna get escaped with backslash but the " is not escaped.
Examples:
def print_it(s):
print(repr(s))
print("-----------------------------------")
print_it('Soroush')
print_it("Soroush")
print_it('Soroush"s book')
print_it("Soroush's book")
print_it('Soroush"s book and Soroush\' pen')
print_it("Soroush's book and Soroush\" pen")
output:
'Soroush'
-----------------------------------
'Soroush'
-----------------------------------
'Soroush"s book'
-----------------------------------
"Soroush's book"
-----------------------------------
'Soroush"s book and Soroush\' pen'
-----------------------------------
'Soroush\'s book and Soroush" pen'
-----------------------------------
So with that being said, the only way to get your desired output is by calling str() on a string.
I know Soroush"s book is grammatically incorrect in English. I just want to put it inside an expression.
Not sure what you want it to print.
Do you want it to output XYZ\'s \"ABC\" or XYZ's "ABC"?
The \ escapes next special character like quotes, so if you want to print a \ the code needs to have two \\.
string = "Im \\"
print(string)
Output: Im \
If you want to print quotes you need single quotes:
string = 'theres a "lot of "" in" my "" script'
print(string)
Output: theres a "lot of "" in" my "" script
Single quotes makes you able to have double quotes inside the string.

Strip function/print in python - why there is no difference for removing whitespace in end

I was just trying out the strip function:
>> a = "hello world "
>> print(a)
hello world
>> print(a.strip())
hello world
There is no difference in the output even though the string has spaces at the end. Could someone explain why?
There is a difference if you check the lengths, you just can't see it when printing;
a = "hello world "
print(len(a))
print(len(a.strip()))
Output:
15
11
There is a difference, you just can't see it because it's whitespace. Try to replace whitespace with a visible character
a = "hello world "
print(a.replace(' ', '+'))
print(a.strip().replace(' ', '+'))
Space characters are not printable, so there won't be a visible difference in the output. To see the difference, try adding and then stripping some printable character:
a = "hello world____"
print(a)
print(a.strip('_'))

python prefix string with backslash

I am looking for a way to prefix strings in python with a single backslash, e.g. "]" -> "]". Since "\" is not a valid string in python, the simple
mystring = '\' + mystring
won't work. What I am currently doing is something like this:
mystring = r'\###' + mystring
mystring.replace('###','')
While this works most of the time, it is not elegant and also can cause problems for strings containing "###" or whatever the "filler" is set to. Is there a bette way of doing this?
You need to escape the backslash with a second one, to make it a literal backslash:
mystring = "\\" + mystring
Otherwise it thinks you're trying to escape the ", which in turn means you have no quote to terminate the string
Ordinarily, you can use raw string notation (r'string'), but that won't work when the backslash is the last character
The difference between print a and just a:
>>> a = 'hello'
>>> a = '\\' + a
>>> a
'\\hello'
>>> print a
\hello
Python strings have a feature called escape characters. These allow you to do special things inside as string, such as showing a quote (" or ') without closing the string you're typing
See this table
So when you typed
mystring = '\' + mystring
the \' is an escaped apostrophe, meaning that your string now has an apostrophe in it, meaning it isn't actually closed, which you can see because the rest of that line is coloured.
To type a backslash, you must escape one, which is done like this:
>>> aBackSlash = '\\'
>>> print(aBackSlash)
\
You should escape the backslash as follows:
mystring = "\\" + mystring
This is because if you do '\' it will end up escaping the second quotation. Therefore to treat the backslash literally, you must escape it.
Examples
>>> s = 'hello'
>>> s = '\\' + s
>>> print
\hello
Your case
>>> mystring = 'it actually does work'
>>> mystring = '\\' + mystring
>>> print mystring
\it actually does work
As a different way of approaching the problem, have you considered string formatting?
r'\%s' % mystring
or:
r'\{}'.format(mystring)

Python Escape Sequence and String Manipulation

I have the following two vars:
a = chr(92) + 'x11'
b = '\x11'
print 'a is: ' + a
print 'b is: ' + b
The result of these print statemtents:
a is: \x11
b is: <| # Here I am just showing a representation of the symbol that is printed for b
How can I make it so that variable a prints the same thing as var b using the chr(92) call? Thank you in advance.
The other answers are showing you how to make b give you what you get in a. If you want a to give you what you get in b (which is what you're asking, if I read you correctly), you need to decode the escape sequence:
>>> a
u'\\x11'
>>> a.decode('string-escape')
'\x11'
You can also use unicode-escape instead of string-escape if you want a unicode string as the result.
Check out the documentation for string literals.
Backslash is an escape character in Python strings, so to include a literal backslash in your string you need to escape them by using two consecutive backslashes. Alternatively, you can suppress the escaping behavior of backslashes by using a raw string literal, which is done by prefixing the string with r. For example:
Escaping the backslash:
b = '\\x11'
Using a raw string literal:
b = r'\x11'
If I am misinterpreting your question and b should be '\x11' or equivalently chr(17), but you just want it to display in the escaped format, you can use repr() for that:
>>> b = '\x11'
>>> print 'b is: ' + repr(b)
b is: '\x11'
If you don't want the quotes, use the string_escape encoding:
>>> print 'b is: ' + b.encode('string_escape')
b is: \x11
Or to get a to be the same as b, you can use a.decode('string_escape').
\x11 appears to be the hex value for a ^Q control character in ASCII:
\021 17 DC1 \x11 ^Q (Device control 1) (XON) (Default UNIX START char.)
You need to escape the \ to get the literal \x11

Python Replace \\ with \ [duplicate]

This question already has answers here:
Process escape sequences in a string in Python
(8 answers)
Closed 7 months ago.
So I can't seem to figure this out... I have a string say, "a\\nb" and I want this to become "a\nb". I've tried all the following and none seem to work;
>>> a
'a\\nb'
>>> a.replace("\\","\")
File "<stdin>", line 1
a.replace("\\","\")
^
SyntaxError: EOL while scanning string literal
>>> a.replace("\\",r"\")
File "<stdin>", line 1
a.replace("\\",r"\")
^
SyntaxError: EOL while scanning string literal
>>> a.replace("\\",r"\\")
'a\\\\nb'
>>> a.replace("\\","\\")
'a\\nb'
I really don't understand why the last one works, because this works fine:
>>> a.replace("\\","%")
'a%nb'
Is there something I'm missing here?
EDIT I understand that \ is an escape character. What I'm trying to do here is turn all \\n \\t etc. into \n \t etc. and replace doesn't seem to be working the way I imagined it would.
>>> a = "a\\nb"
>>> b = "a\nb"
>>> print a
a\nb
>>> print b
a
b
>>> a.replace("\\","\\")
'a\\nb'
>>> a.replace("\\\\","\\")
'a\\nb'
I want string a to look like string b. But replace isn't replacing slashes like I thought it would.
There's no need to use replace for this.
What you have is a encoded string (using the string_escape encoding) and you want to decode it:
>>> s = r"Escaped\nNewline"
>>> print s
Escaped\nNewline
>>> s.decode('string_escape')
'Escaped\nNewline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\\nb".decode('string_escape')
'a\nb'
In Python 3:
>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'
You are missing, that \ is the escape character.
Look here: http://docs.python.org/reference/lexical_analysis.html
at 2.4.1 "Escape Sequence"
Most importantly \n is a newline character.
And \\ is an escaped escape character :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
r'a\\nb'.replace('\\\\', '\\')
or
'a\nb'.replace('\n', '\\n')
Your original string, a = 'a\\nb' does not actually have two '\' characters, the first one is an escape for the latter. If you do, print a, you'll see that you actually have only one '\' character.
>>> a = 'a\\nb'
>>> print a
a\nb
If, however, what you mean is to interpret the '\n' as a newline character, without escaping the slash, then:
>>> b = a.replace('\\n', '\n')
>>> b
'a\nb'
>>> print b
a
b
It's because, even in "raw" strings (=strings with an r before the starting quote(s)), an unescaped escape character cannot be the last character in the string. This should work instead:
'\\ '[0]
In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print statement to see what the string actually looks like.
This example shows the difference:
>>> '\\'
'\\'
>>> print '\\'
\
In Python 3 it will be:
bytes(s, 'utf-8').decode("unicode_escape")
This works on Windows with Python 3.x:
import os
str(filepath).replace(os.path.sep, '/')
Where: os.path.sep is \ on Windows and / on Linux.
Case study
Used this to prevent errors when generating a Markdown file then rendering it to pdf.
path = "C:\\Users\\Programming\\Downloads"
# Replace \\ with a \ along with any random key multiple times
path.replace('\\', '\pppyyyttthhhooonnn')
# Now replace pppyyyttthhhooonnn with a blank string
path.replace("pppyyyttthhhooonnn", "")
print(path)
#Output...
C:\Users\Programming\Downloads

Categories