1.基本使用
①字符串可以用' '
或者" "
括起来表示。
②字符串既包含单引号,又有双引号,用 \ 进行转义
\n表示换行
\t 表示一个制表符
\\表示 \ 字符本身
③转义
1.单行有较多需要转义的,可使用 r'...' (不能表示包含'
和 "
的字符串。)----raw字符串
2.多行字符串,可以用 '''...'''
3.多行字符串前加
r
,也可变成raw字符串
1.r'\(~_~)/ \(~_~)/'
2.如果要表示多行字符串,可以用'''...'''表示:
'''Line 1
Line 2
Line 3'''
上面这个字符串的表示方法和下面的是完全一样的:
'Line 1\nLine 2\nLine 3'
3.还可以在多行字符串前面添加r,把这个多行字符串也变成一个raw字符串:
r'''Python is created by "Guido".
It is free and easy to learn.
Let's start learn Python in imooc!'''
2.format
字符串format由两个部分组成,字符串模板和模板数据内容组成,通过大括号{}
,
就可以把模板数据内容嵌到字符串模板对应的位置。
模板变量.format(模板内容)
# 字符串模板
template = 'Hello {}'
# 模板数据内容
world = 'World'
result = template.format(world)
print(result) # ==> Hello World
# 指定顺序
template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
# 指定{}的名字w,c,b,i
template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.'
# 指定名字对应的模板数据内容
result = template.format(w = world, c = china, b = beijing, i = imooc)
3字符串切片(切片在 [ ] 中填入两个数字,用 :分开,表示字串的开始位置和结束位置,前闭后开)
s = 'ABC'
a = s[0] # 第一个 A
ab = s[0:2] # 结果为AB