Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

python - Including a backslash at the end of a raw triple quoted string fails


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 >

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...