1

If I have a string

dummy_path = "this is a dummy path\basic"

The \b character is of course a backspace, so this get printed (and processed by filesystem calls) as

this is a dummy patasic

(Patasic, nice name!)

Do I have a chance to detect this situation and warn the user (myself) that the \ in dummy_path should be, for example, either escaped or substituted with a /?

3
  • 2
    try print(repr(dummy_path)) Commented Feb 15, 2017 at 15:52
  • 1
    Editor/IDE syntax highlighting will normally mark these sorts of escape sequences in a highly noticeable way. Are you using syntax highlighting? Can it be configured to make these constructs more noticeable to you? Commented Feb 15, 2017 at 15:56
  • 1
    This doesn't exactly answer your question, but consider using a raw string for file paths. r"dummy\basic" will interpret the backslash as just a backslash. Commented Feb 15, 2017 at 16:05

1 Answer 1

3

You can see for yourself:

>>> dummy_path = "this is a dummy path\basic"
>>> dummy_path
'this is a dummy path\x08asic'

The len function also reflects this:

>>> len("a\bc")
3
>>> "a\bc"
'a\x08c'
>>> print("a\bc")
c

as does the in operator with two strings as arguments:

>>> "\b" in "a\bc"
True

How it is displayed is entirely dependent on your output device. Most terminals will print each character one after the other. The \b, instead of being visible, simply repositions the cursor one position to the left, at which point the a overwrites the previously written h.

Notably, this is how a man page displays bold text. Man pages (which are on-screen renderings of *roff code) use letter-backspace-letter sequences to indicate a letter should be displayed in bold face. The metaphor comes from typewriters: to type a letter in bold, you type it once, backspace, then type it again over the first one. Similarly, underlining can be represented as letter-backspace-underscore.

Sign up to request clarification or add additional context in comments.

3 Comments

Use repr (which is what my example, displaying the value in the interactive shell, demonstrates implicitly). dummy_path is a string value, while repr(dummy_path) returns a string that represents a string value, specifically with otherwise unprintable characters replaced with a \x?? representation.
Thanks for your answer, it is just missing a small part regarding how can I detect programmatically the situation, which I suppose it's simply if "\b" in dummy_path:
That's right. The in operator, when both arguments are strings, behaves a little bit differently; it returns True if the first argument is a substring of the second, rather than if the first argument is an element of the second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.