Defining strings
We've explained what strings are in front of us. Strings can be ‘‘
expressed in or ""
enclosed.
What if the string itself contains ‘
? For example, if we want to represent I‘m OK
a string, we can say it in " "
parentheses:
"I ' m OK"
Similarly, if a string is contained "
, we can use it as a ‘ ‘
means of enclosing:
' Learn ' Python "in Imooc '
What if the string contains ‘
and contains both "
?
At this point, you need to "escape" some special characters of the string , and the Python string is \
escaped.
To represent a stringBob said "I‘m OK".
Because ' and ' can cause ambiguity, so we insert a representation before it that \
this is an ordinary character and does not represent the beginning of the string, so the string can be represented as
' Bob said \ ' i\ ' m ok\ '. '
Note: the escape character \ does not count toward the contents of the string.
The usual escape characters are:
\ n indicates a newline \ t means a tab \ \ means \ character itself
Task
Please print the following two lines in a Python string:
Python is started in 1989 by "Guido".
Python is free and easy to learn.
Raw strings and multiple lines of string
If a string contains many characters that need to be escaped, it can be cumbersome to escape each character. To avoid this, we can prefix the string to r
indicate that it is a raw string, and that the characters inside it do not need to be escaped. For example:
R ' \ (~_~)/\ (~_~)/'
However r‘...‘
, the notation cannot represent multiple lines of string, nor can it represent ‘
"
A string containing and (why?). )
If you want to represent multiple lines of string, you can use the ‘‘‘...‘‘‘
expression:
"Line 1Line 2Line 3"
The above string is represented in exactly the same way as the following:
' Line 1\nline 2\nline 3 '
You can also add the multiline string to r
a raw string by adding it in front of it:
R ' ' Python is created by ' Guido '. It's free and easy to learn. Let's start learn Python in imooc! '
Task
Please rewrite the following string in r‘‘‘...‘‘‘
the form of print:
' \ ' to being, or not to be\ ": That's the Question.\nwhether it\ ' s nobler in the mind to suffer. '
Getting Started with Python (i) Defining a string +raw string with multiple lines of string