Charles Morris Charles Morris - 8 days ago 4
Python Question

In Python, how can you write the string String = "\s"?

Why does:

B = "The" + "\s"


and

B = "The" + r"\s"


yield:

"The\\s"


Is it possible to write the above, such that the output string is:

"The\s"


I have read similar questions on both the issue of backslashes, and their property for escaping, and the interpretation of regex characters in Python.

How to print backslash with Python?

Why can't Python's raw string literals end with a single backslash?

Does this mean there is no way to write what I want?

If it is useful, My end goal is to a write a program that adds the regex expression for space (\s) to a string where this such space:

For example, start with:

A = "The Cat and Dog"


After applying the function, this becomes:

B = "The\sCat\sand\sDog"

Answer

I believe this is related to another question

The representation of the string and what it actually contains can differ.

Observe:

>>> B = "The" + "\s"
>>> B
'The\\s'
>>> print B
The\s

Furthermore

>>> A = "The Cat and Dog"
>>> B = str.replace(A, ' ', '\s')
>>> B
'The\\sCat\\sand\\sDog'
>>> print B
The\sCat\sand\sDog