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

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

Escaped 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. The backslash isn’t counted.

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)) 
7 Likes

I just tried this example in codeacademy’s terminal and here are the results that left me somewhat confused, so I would be very thankful for any help:

first of all, typing the following code line didn’t end my string before I thought it would, how is it possible:

message = "I'm hungry"

Then I went with print(len(message)) and it gave me 10. Ok. Finally I created another variable:

message2 = "I\'m hungry"

just to go again with print(len(message2)) and again it gave me 10. The only conclusion I can get from here is that backslash isn’t counted at all in a string’s length. Is it true?

2 Likes

Yes, true. The backslash doesn’t count as a printable character because it has special meaning… Escape. It tells the parser that the character following is printable, not a token.

We would not use it in this case, though, since ' is different from " and will be printed without escapement.

message = 'I\'m hungry'

Now it is actually doing what is expected. Escape and treat as a printable character.

10 Likes

It would be better if the answer said escaped character only count as one, rather than escape characters.

so the escaped " only counts as one.

2 Likes

Hi,
The escape characters are not counted but the double quotes are counted you can check in the link below

1 Like

Yes, absolutely it’s right.

The compiler is never count the sign(SYMBOL) of (") and sign of ( \ ) → back slash operator!
Because they’re used in strings as per limitations.

If you print the following code,
you will get expected output :yo-yo:

password = "theycallme"crazy"91"
print(password)