Python string "" "use and use escape characters

Strings can be enclosed in '' or "".

What if the string itself contains'? For example, if we want to express the string I'm OK, at this time, we can enclose it with "":


Similar to "I'm OK" , if the string contains ", we can enclose it with '':

'Learn "Python" in imooc'
But what if the string contains both "and "?

At this time, some special characters in the string need to be "escaped", and Python strings are escaped with \.

To represent the string Bob said "I'm OK"
because 'and "will cause ambiguity, we insert a \ in front of it to indicate that this is an ordinary character and does not represent the beginning of the string. Therefore, this string is again It can be expressed as

'Bob said “I'm OK”.'
Note: The escape character \ is not included in the content of the string .

Commonly used escape characters are:

\n means newline
\t means a tab character
\ means \ character itself

output a line of string r'...'
output a multi-line string ``'...'''
output a multi-line string containing multiple escape characters r' ''...'''(I don't quite understand the difference with'''...''', please advise)

String slicing
wants to get a part (substring) of a string. At this time, we take a slice to get it. The slice needs to be filled with two numbers in square brackets [], separated by a colon, indicating the start and end of the substring Position, and this is a half-closed half-open interval, excluding the last position.

ab = s[0:2] # Take the first character to the third character in the string s, excluding the third character
s ='ABC'
a = s[0] # The first
b = s[ 1] # The second
c = s[2] # The third
print (s[0:2])

Guess you like

Origin blog.csdn.net/angelsweet/article/details/109142142