1、字符串表现形式
单引号或是双引号形式
>>> 'hello'
'hello'
>>> "hello"
"hello"
2、多行字符串
三重引号,"""…""" 或 ‘’’…’’’
"""
hello
python
"""
3、字符串合并
使用+号合并字符串
>>> 'py' + 'thon'
'python'
4、字符串重复
使用*生成重复字符串
>>> 3*'hello'
'hellohellohello'
5、字符串自动合并
相邻的两个或多个字符串(引号标注的字符)会自动合并
>>> 'Py' 'thon'
'Python'
拆分长字符串时,这个功能特别实用:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
注:
这项功能只能用于两个字面值,不能用于变量或表达式
合并多个变量,或合并变量与字面值,要用 +
6、字符串索引
字符串支持索引(下标访问),第一个字符的索引是 0。
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
索引还支持负数,用负数索引时,从右边开始计数
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
7、字符串切片
字符串支持切片,即提取子字符串
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
8、字符串修改
为字符串中某个索引位置赋值会报错,要生成不同的字符串,应新建一个字符串
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
9、字符串长度
内置函数 len() 返回字符串的长度
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34