How are escape characters counted towards the length of a string?


#1

Question

In the context of this exercise, if we have escape characters in a string, how are they counted towards the length of the string?

Answer

Escape characters in Python only count as 1 towards a string’s length, like a single character would. So, for the escape character \", this will actually only count as 1 towards the length, rather than 2.

Example

# Because \’ is an escape character, it will only be 
# counted as 1 toward the length of the string.
message = "I\'m hungry"

# length is 10 (includes the space character)
print(len(message))