>>>'spam eggs''spam eggs'>>>'doesn\'t'"doesn't">>>"doesn't""doesn't">>>'"Yes," he said.''"Yes," he said.'>>>"\"Yes,\" he said."'"Yes," he said.'>>>'"Isn\'t," she said.''"Isn\'t," she said.'
>>>'"Isn\'t," she said.''"Isn\'t," she said.'>>>print('"Isn\'t," she said.')"Isn't," she said.>>> s ='First line.\nSecond line.'# \n 意味着新行>>> s # 不使用 print(), \n 包含在输出中'First line.\nSecond line.'>>>print(s)# 使用 print(), \n 输出一个新行
First line.
Second line.
以下使用反斜线(\)来续行:
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print(hello)
注意,其中的换行符任然要使用\n表示–反斜杠后的换行符被丢弃了。以上例子将如下输出:
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Usage: thingy [OPTIONS]-h Display this usage message
-H hostname Hostname to connect to
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)
This is a rather long string containing\nseveral lines of text much as you would do in C.
字符串可以使用+运算符串连在一起,或者用*运算符重复:
>>> word ='Help'+'A'>>> word
'HelpA'>>>'<'+ word*5+'>''<HelpAHelpAHelpAHelpAHelpA>'
>>> word[0]='x'
Traceback (most recent call last):
File "", line 1,in ?
TypeError:'str'object does not support item assignment
>>> word[:1]='Splat'
Traceback (most recent call last):
File "", line 1,in ?
TypeError:'str'object does not support slice assignment