Python基础数据类型之字符串
一、Python如何创建字符串
在python中用引号将一些文本包起来就构成了字符串(引号可以是单引号、双引号、单三引号,双三引号,它们是完全相同的)
>>> str1 = 'hello'
>>> str2 = "hello"
>>> str3 = '''hello'''
>>> str4 = """hello"""
>>> type(str1)
<class 'str'>
>>> type(str2)
<class 'str'>
>>> type(str3)
<class 'str'>
>>> type(str4)
<class 'str'>
>>> str1 == str2 == str3 == str4
True
三引号还可以保存字符串的原始格式
>>> str5 = """
... Hello everyone,
... nice to meet you,
... my name is Keys,
... I am 27 years old"""
>>> str5
'\nHello everyone,\nnice to meet you,\nmy name is Keys,\nI am 27 years old'
>>> print(str5) Hello everyone,
nice to meet you,
my name is Keys,
I am 27 years old
>>>
二、Python中字符串的基本注意事项
#1.当字符串中有引号时,包裹字符串的引号不能和字符串中的引号相同
#2.当字符串中有可能构成转义字符时,要注意对\进行转义
#3.字符串是不可变类型,一旦给定不可修改
三、字符串常用基本操作
#1.字符串相加
>>> str1 = 'Keys'
>>> str2 = 'HongPing'
>>> str3 = str1+str2
>>> str3
'KeysHongPing'
>>>
#2.字符串与数字相乘
>>> str1 = 'Keys'
>>> str1*10
'KeysKeysKeysKeysKeysKeysKeysKeysKeysKeys'
>>>
四、字符串方法
1.capitalize()
把字符串的第一个字符改为大写
>>> str1 = 'keys'
>>> str1.capitalize()
'Keys'
>>>
2.casefold()
把整个字符串的所有字符改为小写
>>> str1 = 'KEYS'
>>> str1.casefold()
'keys'
>>>
3.center(width)
将字符串居中,并使用空格填充至长度为width的新字符串
>>> str1 = 'Keys'
>>> str1.center(10)
' Keys '
>>>
4.count(sub[, start[, end]])
返回sub在字符串里出现的次数,start和end参数表示范围,可选
>>> str1 = 'hello'
>>> str1.count('l')
2
>>> str1.count('h')
1
>>> str1.count('h',1,5)
0
>>> str1.count('h',0,3)
1
>>>
5.encode(encoding='utf-8', errors='strict')
以encoding指定的编码格式对字符串进行编码
>>> str1 = 'Keys'
>>> str1.encode(encoding='utf-8')
b'Keys'
>>>
6.endswith(sub[, start[, end]])
检查字符串是否以sub子字符串结束,如果是返回True,否则返回False,start和end参数表示范围,可选
>>> str1 = 'Keys'
>>> str1.endswith('s')
True
>>> str1.endswith('K')
False
>>> str1.endswith('K',1,3)
False
>>> str1.endswith('s',1,3)
False
>>>
7.expandtabs([tabsize=8])
把字符串中的tab(\t)符号转换为空格,如果不指定参数,默认的空格数是tabsize=8
>>> str1 = 'Keys\tNotebook'
>>> str1.expandtabs()
'Keys Notebook'
>>> str1 = 'Keys\tNotebook'
>>> str1.expandtabs(tabsize=2)
'Keys Notebook'
>>>
8.find(sub[, start[, end]])
检查sub是否在字符串中,如果是,返回索引值,否则返回-1,start和end参数表示范围,可选
>>> str1 = 'Keys'
>>> str1.find('e')
1
>>> str1.find('e',2,4)
-1
>>> str1.find('A')
-1
>>>
9.format()
format()方法用于对字符串进行格式化,它可以接受位置参数和关键字参数,具体用例如下:
#1.位置参数
>>> '{0} love {1}'.format('I','YOU')
'I love YOU'
>>>
#2.关键字参数
>>> '{a} love {b}'.format(a='I',b='YOU')
'I love YOU'
>>>
#3.位置参数和关键字参数可以混合使用,但是位置参数必须在关键字参数之前
>>> '{0} love {b}'.format('I',b='YOU')
'I love YOU'
>>>
10.format_map()
将字典中的参数传递进字符串中,输出
>>> str1 = "My name is {name},I come from {country}."
>>> str1.format_map({'name':'Keys','country':'China'})
'My name is Keys,I come from China.'
>>>
11.index(sub[, start[, end]])
检查sub是否在字符串中,如果是,返回索引值,否则会产生一个异常,start和end参数表示范围,可选。
>>> str1 = 'Keys'
>>> str1.index('K')
0
>>> str1.index('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> str1.index('K',2,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
12.isalnum()
如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False
>>> str1 = 'Keys'
>>> str2 = ''
>>> str3 = '%&12K'
>>> str4 = ''
>>> str1.isalnum()
True
>>> str2.isalnum()
True
>>> str3.isalnum()
False
>>> str4.isalnum()
False
>>>
13.isalpha()
如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False
>>> str1 = 'qwert'
>>> str2 = 'Keys666'
>>> str3 = ''
>>> str1.isalpha()
True
>>> str2.isalpha()
False
>>> str3.isalpha()
False
>>>
14.isdecimal()
如果字符串只包含十进制数字则返回True,否则返回False
>>> str1 = ''
>>> str2 = 'Keys888'
>>> str3 = '0xFF'
>>> str1.isdecimal()
True
>>> str2.isdecimal()
False
>>> str3.isdecimal()
False
>>>
15.isdigit()
如果字符串只包含数字则返回True,否则返回False
>>> str1 = ''
>>> str2 = 'Keys668'
>>> str3 = ''
>>> str1.isdigit()
True
>>> str2.isdigit()
False
>>> str3.isdigit()
False
>>>
16.isidentifier()
判断是不是一个合法的标识符
>>> str1 = '123%'
>>> str2 = 'Keys'
>>> str3 = '_keys'
>>> str4 = '666Keys'
>>> str1.isidentifier()
False
>>> str2.isidentifier()
True
>>> str3.isidentifier()
True
>>> str4.isidentifier()
False
>>>
17.islower()
如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写则返回True,否则返回False
>>> str1 = 'keys'
>>> str2 = 'Keys'
>>> str3 = 'keys666'
>>> str1.islower()
True
>>> str2.islower()
False
>>> str3.islower()
True
>>>
18.isnumeric()
如果字符串中只包含数字字符则返回True,否则返回False
>>> str1 = ''
>>> str2 = 'hello666'
>>> str1.isnumeric()
True
>>> str2.isnumeric()
False
>>>
19.isprintable()
判断是否为可打印字符串
>>> str1 = ''
>>> str2 = '\t'
>>> str1.isprintable()
True
>>> str2.isprintable()
False
>>>
20.isspace()
如果字符串中只包含空格则返回True,否则返回False
>>> str1 = ' '
>>> str2 = 'Hello Keys'
>>> str1.isspace()
True
>>> str2.isspace()
False
>>>
21.istitle()
如果字符串是标题化(所有单词第一个字符大写,其余都是小写)
>>> str1 = 'Hello World'
>>> str2 = 'How are you'
>>> str1.istitle()
True
>>> str2.istitle()
False
>>>
22.isupper()
如果字符串中至少包含一个区分大小写的字符,并且这些字符都是大写则返回True,否则返回False
>>> str1 = 'KEYS'
>>> str2 = 'KEYS668'
>>> str3 = 'Keys'
>>> str1.isupper()
True
>>> str2.isupper()
True
>>> str3.isupper()
False
>>>
23.join(sub)
以字符串为分隔符,插入到sub中所有字符之间
>>> str = ':'
>>> str.join('KEYS')
'K:E:Y:S'
>>>
24.ljust(width)
返回一个左对齐的字符串,并用空格填充至宽度为width的字符串
>>> str1 = 'Keys'
>>> str1.ljust(8)
'Keys '
>>> str1.ljust(16)
'Keys '
>>>
25.lower()
转换字符串所有大写字符为小写
>>> str1 = 'KEYS'
>>> str1.lower()
'keys'
>>>
26.lstrip()
去掉字符串左边所有空格
>>> str1 = ' Keys'
>>> str1.lstrip()
'Keys'
>>>
27.maketrans()
用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
注:两个字符串的长度必须相同,为一一对应的关系
>>> a= 'abcd'
>>> b= ''
>>> str_tran = str.maketrans(a,b)
>>> str1 = 'how about you'
>>> str1.translate(str_tran)
'how 12out you'
>>>
28.partition(sub)
找到字符串sub,将字符串分成一个三元组(before_sub,sub,after_sub),如果字符串中没有sub,则返回(原字符串,'','')
>>> str1 = 'Keys'
>>> str1.partition('e')
('K', 'e', 'ys')
>>>
29.replace(old, new[, count])
把字符串中的old子字符串替换成新的new子字符串,如果指定count,则替换不超过count次
>>> str1 = 'Keys'
>>> str1.replace('K','k')
'keys'
>>> str2 = 'KKKKeys'
>>> str2.replace('K','k',2)
'kkKKeys'
>>>
30.rfind(sub[, start[, end]])
类似于find()方法,不过是从右边开始查找
>>> str1 = 'Keysy'
>>> str1.rfind('y')
4
>>> str1.rfind('y',1,3)
2
>>>
31.rindex(sub[, start[, end]])
类似于index()方法,不过是从右边开始查找
>>> str1 = 'Keysy'
>>> str1.rindex('y')
4
>>> str1.rindex('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> str1.rindex('y',1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
32.rjust(width)
返回一个右对齐的字符串,并用空格填充至宽度为width的字符串
>>> str1 = 'Keys'
>>> str1.rjust(8)
' Keys'
>>> str1.rjust(16)
' Keys'
>>>
33.rpartition(sub)
类似于partition()方法,但是从右边开始查找
>>> str1 = 'KeyyeKy'
>>> str1.rpartition('e')
('Keyy', 'e', 'Ky')
>>>
34.rsplit()
通过指定分隔符对字符串进行分割并返回一个列表,默认分隔符为所有空字符,包括空格、换行(\n)、制表符(\t)等。类似于 split() 方法,只不过是从字符串最后面开始分割。
35.rstrip()
删除字符串末尾的空格
>>> str1 = 'Keys '
>>> str1.rstrip()
'Keys'
>>>
36.split(sep=None, maxsplit=-1)
不带参数默认是以空格作为分隔符切片字符串,如果设置maxsplit参数,则仅分隔maxsplit个子字符串,返回切片后子字符串组成的列表
>>> str1 = 'Keys:Keys:Keys:Keys'
>>> str1.split(':')
['Keys', 'Keys', 'Keys', 'Keys']
>>> str1.split(':',2)
['Keys', 'Keys', 'Keys:Keys']
>>>
37.splitlines(([keepends]))
按照'\n'分隔,返回一个包含各行作为元素的列表
>>> str1 = 'Keys\nKeys\nKeys\nKeys\n'
>>> str1.splitlines()
['Keys', 'Keys', 'Keys', 'Keys']
38.startswith(prefix[, start[, end]])
检查字符串是否以sub子字符串开始,如果是返回True,否则返回False,start和end参数表示范围,可选
>>> str1 = 'Keys'
>>> str1.startswith('K')
True
>>> str1.startswith('k')
False
>>> str1.startswith('K',2,4)
False
>>>
39.strip()
删除字符串前边和后边的所有空格
>>> str1 = ' keys '
>>> str1.strip()
'keys'
>>>
40.swapcase()
反转字符串中的大小写
>>> str1 = 'Keys'
>>> str1.swapcase()
'kEYS'
>>>
41.title()
返回标题化(所有单词第一个字符大写,其余都是小写)的字符串
>>> str1 = 'hello python'
>>> str1.title()
'Hello Python'
>>>
42.translate(table)
根据table的规则(可由str.maketrans('a','b')定制)
43.upper()
转换字符串所有小写字符为大写
>>> str1 = 'keys'
>>> str1.upper()
'KEYS'
>>>
44.zfill(width)
返回长度为width的字符串,原字符串右对齐,前边用0填充
>>> str1 = 'Keys'
>>> str1.zfill(10)
'000000Keys'
>>>