目录
字符串
字符串的定义
字符串是 Python 中最常用的数据类型。我们一般使用引号来创建字符串。创建字符串很简单,只要为变量分配一个值即可。
a = 'Hello Python!'
b = "abcd1234"
print(type(a)) #<class 'str'>
print(type(b)) #<class 'str'>
#三引号字符串(支持换行)
name = '''i am tom,
nihao.'''
name
#'i am tom,\n nihao.'
创建一个字符串:I'm Tom.
a = "I'm Tom." #"I'm Tom."
字符串也可以通过索引下标来获得每一个字符。(索引下标从零开始)
字符串切片
切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。
序列[开始位置下标(包含):结束位置下标(不包含):步长(默认为1)]
字符串常用操作方法
1.查找方法:
find():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则返回-1。
mystr = 'hello world and hello python'
print(mystr.find('hello')) # 0
print(mystr.find('hello', 10, 27)) #16
print(mystr.find('shuaige')) # -1
index():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则报异常。
mystr = "hello world and hello python"
print(mystr.index('hello')) # 0
print(mystr.index('hello', 10, 27)) #16
print(mystr.index('shuaige')) # 报错
2.字符串修改
replace():返回替换后的字符串
mystr = "hello world and hello python"
# 结果:hello world & hello python
print(mystr.replace('and', '&'))
# 结果:hi world and hi python
print(mystr.replace('hello', 'hi', 2))
# 结果:hello world and hello python
print(mystr)
split():按照指定字符分割字符串。
mystr = 'apple,orange,banana'
# 结果:['apple', 'orange', 'banana']
print(mystr.split(','))
# 结果:['apple', 'orange,banana']
print(mystr.split(',', 1))
# 结果:['apple,orange,banana']
print(mystr.split('*'))
join():用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串。
list1 = ['it', 'heima']
tuple1 = ('hello', 'python')
# 结果:itheima
print(''.join(list1))
# 结果:hello-python
print('-'.join(tuple1))
upper():将字符串中小写转大写
lower():将字符串中大写转小写
3.字符串判断
startswith():检查字符串是否是以指定子串开头,是则返回 True,否则返回 False。如果设置开始和结束位置下标,则在指定范围内检查。
endswith():检查字符串是否是以指定子串结尾,是则返回 True,否则返回 False。如果设置开始和结束位置下标,则在指定范围内检查。
列表
a = [1, 2, 3, 4, 5]
列表操作方法
1.列表查询
index()方法:指定数据所在位置的下标
name_list = [‘Tom’, ‘Lily’, ‘Rose’]
print(name_list.index(‘Lily’, 0, 2)) #结果:1
count()方法:统计指定数据在当前列表中出现的次数
in:判断指定数据在某个列表序列,如果在返回True,否则返回False
not in:判断指定数据不在某个列表序列,如果不在返回True,否则返回False
2.列表的增添
append()方法:增加指定数据到列表中
name_list = ['Tom', 'Lily', 'Rose']
name_list.append('Jennifer')
print(name_list) #['Tom', 'Lily', 'Rose', 'Jennifer']
extend()方法:列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一添加到列表
name_list = ['Tom', 'Lily', 'Rose']
name_list.extend('Jennifer')
name_list
# ['Tom', 'Lily', 'Rose', 'J', 'e', 'n', 'n', 'i', 'f', 'e', 'r']
insert()方法:指定位置新增数据
name_list = ['Tom', 'Lily', 'Rose']
name_list.insert(1, 'Smith')
# 结果:['Tom', 'Smith', 'Lily', 'Rose']
print(name_list)
3.列表的删除
del:删除列表中的某个元素
pop()方法:删除指定下标的数据(默认为最后一个),并返回该数据。
name_list = ['Tom', 'Lily', 'Rose']
del_name = name_list.pop(1)
# 结果:Lily
print(del_name)
# 结果:['Tom', 'Rose']
print(name_list)
remove()方法:移除列表中某个数据的第一个匹配项。
clear()方法:清空列表,删除列表中的所有元素,返回空列表。
4.列表的修改
reverse():将数据序列进行倒叙排列
sort()方法:对列表序列进行排序
num_list = [1, 5, 2, 3, 6, 8]
num_list.sort()
print(num_list) #[1, 2, 3, 5, 6, 8]
num_list.sort(reverse = True)
print(num_list) #[8, 6, 5, 3, 2, 1]