重新梳理一遍python的基础知识
- 除了数字,Python 还可以操作字符串。字符串有多种表现形式,用单引号(
'……')或双引号("……")标注的结果相同 。反斜杠\用于转义:
>>>'spam eggs' # 直接输出 ‘spam eggs’
>>> "doesn't" * # 使用双引号直接输出"doesn’t"
>>> 'doesn\'t' # 使用\'转义单引号
"doesn't"
- 不需要在单引号里转义双引号
",但需要转义字符串里的单引号\'。
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
反过来,也不需要在双引号里转义单引号 ' ,但需要转义字符串里的双引号 \" 。
>>>"\"Yes,\" they said."
'"Yes," they said.'
- 特殊字符如
\n在单引号('...')和双引号("...")里的意义一样。
如果不希望前置\的字符转义成特殊字符,可以使用 原始字符串,在引号前添加r即可
>>>print('C:\some\name') #这里的\n换行
C:\some
\ame
>>>print(r'C:\some\name')
C:\some\name
>>>s = 'First line.\nSecond line.'
>>>s # 没有 print() 时, \n 被包含在输出中
'First line.\nSecond line.'
>>>print(s) # 有 print() 时, \n 换行
First line.
Second line.
- 以奇数个反斜杠结尾的原始字符串将会转义用于标记字符串的引号。
>>> r'C:\this\will\not\work\' 会报错
可以使用双反斜杠:
>>> 'C:\\this\\will\\work\\'
'C:\\this\\will\\work\\'
也可以这样写:‘C:/this/will/not/work/’
在 Windows 系统上还可以使用 [os.path.join()]来添加反斜杠:
>>> os.path.join(r'C:\this\will\work', '') 'C:\\this\\will\\work\\'
- 字符串字面值可以包含多行。 一种实现方式是使用三重引号:
"""..."""或'''...'''。 字符串中将自动包括行结束符,但也可以在换行的地方添加一个\来避免此情况。
print("""\
Usage: thingy -h -H hostname
""")
输出如下:

不添加\ 的效果
