This question has already been documented on Python FAQ documentation. So you can read through the details.
Extract from the FAQ:
Why can’t raw strings (r-strings) end with a backslash? More
precisely, they can’t end with an odd number of backslashes: the
unpaired backslash at the end escapes the closing quote character,
leaving an unterminated string.
Raw strings were designed to ease creating input for processors
(chiefly regular expression engines) that want to do their own
backslash escape processing. Such processors consider an unmatched
trailing backslash to be an error anyway, so raw strings disallow
that. In return, they allow you to pass on the string quote character
by escaping it with a backslash. These rules work well when r-strings
are used for their intended purpose.
Unfortunately there is no way around it. You need to end it with another character or include a space. If you include a space, the length will change.
The trick to get the backslash as the last string is to add a space after the backslash.
char = r'''|'*+[]".?!-/,{}()&%$_;:#@=`~<>^\ '''
print ('last char:',char[-1], 'second last char', char[-2],'third last char', char[-3])
Here's the output of the above code:
last char: second last char \ third last char ^
So you have to just change it to another character. The reason is \
is an escape character and it is taking the '
as a char.
My initial reaction was to add another backslash. However, that just adds the backslash to the string. See code below.
char = r'''|'*+[]".?!-/,{}()&%$_;:#@=`~<>^\\'''
print ('last char:',char[-1], 'second last char', char[-2],'third last char', char[-3])
The output is:
last char: \ second last char \ third last char ^
The only workaround I found is to include the space but to slice the string to [:-1]. You can do the following:
char = r'''|'*+[]".?!-/,{}()&%$_;:#@=`~<>^\ '''[:-1]
print ('last char:',char[-1], 'second last char', char[-2],'third last char', char[-3])
The output of this will be:
last char: \ second last char ^ third last char >