What does backward-slash b do in Python?
Asked Answered
F

2

28

What is the purpose of backward-slash b in python? I ran print "\"foo\bar" in the Python interpreter and got this result:

>>> print "\"foo\bar"
"foar
Fullrigged answered 31/7, 2014 at 17:44 Comment(4)
en.wikipedia.org/wiki/Escape_characterSheepshearing
Why the down votes? This is a perfectly legitimate question that's hard to answer via google if you don't already know about ascii escape characters.Presber
@dshepherd: I can't speak for the voters, since I didn't vote either way, but a lot of people would rather people looked in the docs instead of googling in the first place, and also complain about the fact that SO questions and answers that duplicate information in the docs just make googling even harder. (Personally, even if they're right, I can't see how downvoting without a comment helps nearly as much as adding a comment…)Rheinlander
@Presber that was my whole point, I couldn't find the answer on Google and thus asked this question here. I think I should find some other python community, and ask these kind of 'stupid' questions there. Thank you all for the comments though :)Fullrigged
C
23

See the string literal documentation:

\b ASCII Backspace (BS)

It produces a backspace character. Your terminal backspaced over the second o when printing that character.

Cirillo answered 31/7, 2014 at 17:48 Comment(2)
I used \r \t \b on cmd(Windows). All of these worked . How do I know that a specific console support a specific escape sequence or not? @martijn-pietersDoug
@Pie: that's way too broad a question, too many variables. Try it out on the console in question is probably easiest.Cirillo
S
5

The \b is a back space character

\b  ASCII Backspace (BS)

If you want to print the string \foo\bar do this:

>>> print r"\foo\bar"
\foo\bar

This utilizes the raw strings available in python.

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences

Supernatural answered 31/7, 2014 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.