1 索引
字符串内的字符通过索引来访问
索引也成为下标
字符索引不能越界
>>> a= 'afe'
>>> a
'afe'
>>> a[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
2 切片
s[起始索引:结束索引:步长]
含起始,不含结束值
>>> a = 'hello'
>>> a[1:4]
'ell'
>>> a[1:]
'ello'
>>> a[:4]
'hell'
>>> a[:]
'hello'
>>> a[-1:-4]
''
>>> a[-1:-4:1]
''
>>> a[-1:-4:-1]
'oll'
>>> a[1:4:1]
'ell'
>>> a[1:4:-1]
''
>>> a[4:1:1]
''
>>> a[4:1:-1]
'oll'
>>> a[::2]
'hlo'
>>> a[::-2]
'olh'
3 删除字符串
del str
str = 'abcd'
del str
4 字符串转义
\(在尾行时) 续行符
\\ 反斜杠
\' 单引号
\" 双引号
\O 空
\n 换行
\r 回车
5 raw字符串
r"字符串"
r'字符串'
该表达形式可以使转义字符失效
但对三引号字符串不起作用
print('\n')
print(r'\n')
r'\n\rafaiogha'
6 字符串运算
6.1 字符串连接
”+“
>>> a = "123"
>>> b = "456"
>>>> "123""456"
'123456'
>>> ab
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ab' is not defined
>>> a+b
'123456'
注意:
两个或多个字符串(封闭的引号隔开)相邻时,则自动链接成一个字符串。
与用加号“+”效果一样。
6.2 重复输出字符串
”*“
>>> m = "abc"
>>> m*2
'abcabc'
>>> m*3
'abcabcabc'
6.3 成员运算符
>>> "a" in "abc"
True
>>> "1" not in "234"
True
in 如果字符串中包括有给定的字符串,则返回True
not in 如果字符串中不包括给你的字符串时返回True
7 Unicode字符串
.py文件中显示指定utf-8编码
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
8 内建函数处理字符串
8.1 ord函数
得到一个字符的ASCII值
ord(单个字符的字符串)
错误的写法
>>> ord(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 3 found
>>> ord('ab')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
正确的写法
>>> ord('a')
97
>>> ord('1')
49
8.2 chr函数
得到数字对应的ASCII字符
>>> chr(97)
'a'
>>> chr(1)
'\x01'
>>> chr(49)
'1'
8.3 str函数
将对象转换成合理的字符串
>>> str(12)
'12'
>>> str('abc')
'abc'
>>> str(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'l' is not defined
>>> str(abc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
8.4 len()函数
获得字符串长度
8.5 min()函数
获得字符串中最小值
>>> min('abc')
'a'
8.6 max()函数
获得字符串中最大值
>>> max('abc')
'c'