26

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
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
hky404
  • 1,039
  • 3
  • 17
  • 35
  • http://en.wikipedia.org/wiki/Escape_character – Ashwini Chaudhary Jul 31 '14 at 17:45
  • 11
    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. – dshepherd Jul 31 '14 at 17:52
  • 2
    @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…) – abarnert Jul 31 '14 at 17:53
  • 3
    @dshepherd 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 :) – hky404 Jul 31 '14 at 17:56

2 Answers2

20

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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-pieters – Pie Feb 17 '20 at 18:00
  • 1
    @Pie: that's way too broad a question, too many variables. Try it out on the console in question is probably easiest. – Martijn Pieters Feb 17 '20 at 18:00
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

Andy
  • 49,085
  • 60
  • 166
  • 233