-4

I recently noticed that the symbol \ behaves differently in a python string than other characters.

For example: print('ab' + '\cde') prints ab\cde as expected, but print('a'+'\bcde') only prints cde.

I was wondering what the reason for this was. I am currently using python 11, so it may be a glitch with the new version? Only thing I can think of so far.

Arkleseisure
  • 416
  • 5
  • 19
  • 3
    Not only Python. Most programming languages use \ for escape sequences. `\n` is used for newlines for example. This isn't a glitch or a new change – Panagiotis Kanavos Aug 10 '23 at 15:56
  • [Tutorial](https://www.w3schools.com/python/gloss_python_escape_characters.asp#:~:text=To%20insert%20characters%20that%20are,character%20you%20want%20to%20insert.) – Barmar Aug 10 '23 at 15:57
  • Yup, makes sense, just seemed weird when encountered in the wild. – Arkleseisure Aug 10 '23 at 16:02
  • 1
    In second print '\b' is being treated as backspace character escape sequence, hence you are getting the output as cde. if you want to print it, you can use print('a'+'\\bcde') – ZKS Aug 10 '23 at 16:02
  • Note that \c doesn't show this behaviour, because it's not an escape sequence. Python then chooses to print this as normal. Try `print('a\tb')`, resulting in a tab inserted, or `print('a\ub')`, which prints a\ub as "normal". \v, vertical tab, is perhaps one of the more confusing ones. – 9769953 Aug 10 '23 at 16:05

1 Answers1

1

The \ character is used for escape sequences in many programming languages, including Python. Here's a link to python's escape sequences if you wanted to see some of them.

The reason

print('a'+'\bcde')

only prints

cde

is because \b is the escape sequence for a backspace character. So it will move back one character (backspace), and the next character printed, c, overwrites the a. If you need to print a \ character, use \\. However, as you noticed

print('ab' + '\cde')

does not have a similar effect, and instead prints

ab\cde

This is because \c is not an escape sequence, and instead, Python will print the string the way it is.

Resources:

9769953
  • 10,344
  • 3
  • 26
  • 37
Borisonekenobi
  • 469
  • 4
  • 15