一、什么是字符串
字符串就是一系列字符,在最新的Python 3版本中,字符串是以Unicode编码的,也就是说,Python的字符串支持多语言,Python中用单引号、双引号括起来的都是字符串,例如:
"Learn Python."
'Learn Python.'
你还可以混合使用单引号和双引号:
'I am learning "Python".'
"I am learning 'Python'."
二、字符串常见操作
1、修改字符串大小写
>>>str = 'hello world.'
# 将字符串每个单词首字母改为大写
>>>str.title()
'Hello World'
# 将字符串全部改为大写
>>>str.upper()
'HELLO WORLD'
# 将字符串全部改为小写
>>>str.lower()
'hello world'
2、字符串拼接
>>>str1 = 'I am'
>>>str2 = 'learning Python'
>>>str1 + ' ' + str2
'I am learning Python'
3、删除空白
>>>language = ' Pyt hon '
# 删除字符串尾部空白
>>>language.rstrip()
' Pyt hon'
# 删除字符串开头空白
>>>language.lstrip()
'Pyt hon '
# 删除字符串两端空白
>>>language.strip()
'Pyt hon'
# 删除字符串全部空白(即字符串替换)
>>>language.replace(' ','')
'Python'
4、字符串查找
>>>str = 'hello world'
# 查找字符串'w',返回'w'的index,找不到返回-1
>>>str.find('w')
6
# 和find()类似,但是从字符串右边开始查找
>>>str.rfind('w')
6
5、分割字符串
>>>str = 'Python,Java,C++'
# 用','分割,返回一个列表
>>>str.split(',')
['Python', 'Java', 'C++']
6、字符串截取
>>>str = 'abcdefg'
# 用切片操作来截取,0代表开始截取的index,3代表截取的长度
>>>str[0:3]
'abc'
7、字符串翻转
>>>str = 'Python'
# 使用切片
>>>str[::-1]
'nohtyP'
8、判断字符串是否相等
>>>'abc' == 'Abc'
False
>>>'abc' == 'abc'
True
9、字符串长度
str = 'Python'
>>>len(str)
6
10、判断是否是纯字母、数字
# 纯数字、字母
>>>'Abc123'.isalnum()
True
# 纯字母
>>>'Abc'.isalpha()
True
# 纯数字
>>>'123'.isdigit()
True
11、判断是否以指定字符串开头、结尾
# 是否以指定字符串开头
>>>'abcde'.startswith('ab')
True
# 是否以指定字符串结尾
>>>'abcde'.endswith('de')
True
12、将原字符串用空格填充成指定长度的字符串,原字符串居中
# 'abc'的前后各填充两个空格
>>>'abc'.center(7)
' abc '
13、计算指定字符串在原字符串中出现的次数
>>>'abcdabcd'.count('bc')
2
14、是否只包含空格
>>>'a b c'.isspace()
False
>>>' '.isspace()
True
15、字符和编码转换
# 获取字符的整数编码
>>>ord('B')
66
# 把编码转换为对应的字符
>>>chr(66)
'B'
16、字符串编码、解码
# 编码
>>>bb = '中国'.encode(encoding='GBK', errors='ignore')
>>>bb
b'\xd6\xd0\xb9\xfa'
# 解码
bb.decode(encoding='GBK', errors='ignore')
'中国'
17、bytes类型数据
# bytes类型的数据用带b前缀的单引号或双引号表示
m = b'abc'
18、使用原始字符串
>>>print('\tabcd')
'abcd'
# 添加 'r' 后 \t 将不被当做转义字符
>>>print(r'\tabcd')
'\tabcd'
19、字符串格式化
# %运算符用来格式化字符串
>>>'Hello %s' % 'world'
'Hello, world'
>>>'I am %d years old' % 18
'Hello, world'
>>>'I have %d %s' % (10, 'apple')
'I have 10 apple'
常用占位符:
| 占位符 | 说明 |
|---|---|
| %s | 字符串 |
| %d | 整数 |
| %f | 浮点数 |
| %x | 十六进制数 |
三、字符串常量
先导入string模块:
import string
| 常量 | 含义 |
|---|---|
| string.ascii_lowercase | 'abcdefghijklmnopqrstuvwxyz' |
| string.ascii_lowercase | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| string.ascii_letters | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| string.digits | '0123456789' |
| string.octdigits | '01234567' |
| string.hexdigits | '123456789abcdefABCDEF' |
| string.punctuation | 标点符号:'!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~' |
| string.whitespace | 空白字符:' \t\n\r\x0b\x0c' |
| string.printable | 所有的数字、字母、标点符号、空白字符 |