Python爬虫入门 ~ 数据类型常用API(一)

63 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第7天,点击查看活动详情

数据类型相关API

字符串

字符串中,常见的API有如下几种:

  • len
  • find
  • startswith
  • endswith
  • count
  • replace
  • split
  • upper
  • lower
  • strip
  • join

len:获取字符串长度

str = "Hello Python!"
print("len: ", len(str))

image.png

find:找到括号中字符串在目标字符串中第一次出现的位置索引值

print("find: ", str.find("Python"))

image.png startswith:判断字符串是否以括号中的子串开头

print("startswith: ", str.startswith("Python!"))

image.png endswith: 判断字符串是否以括号中的子串结尾

print("endswith: ", str.endswith("Python!"))

image.png count:统计字符串在 start 和 end 直接出现的次数,不填默认搜索整个字符串

print("count: ", str.count("o", 2, 10))

image.png replace:替换字符串中指定的内容,如果指定次数,则替换不会超过指定的次数

print("replace: ", str.replace("o", "0", 1))

image.png split:通过指定内容切割字符串

print("split: ", str.split(" "))

image.png upper:将字符串转换为大写

print("upper: ", str.upper())

image.png lower:将字符串转换为小写

print("lower: ", str.lower())

image.png strip:去除字符串前后的空格

print("strip: ", str.strip())

image.png

列表

添加元素

列表中常见的新增API有如下几种:

  • append
  • insert
  • extend

append:在末尾添加元素

list = [1, 2, 3]
list.append(4)
print(list)

image.png

insert:在指定位置插入元素

list = [1, 2, 3]
list.insert(2, 4)
print(list)

image.png

extend:合并两个列表

list = [1, 2, 3]
list2 = [4, 5, 6]
# 合并两个列表
list.extend(list2)
print(list)

image.png

修改元素

list = [1, 2, 3]
# 修改列表索引处元素值
list[1] = 4
print(list)

image.png

查找元素

查找列表元素常用的有如下几个API:

  • in
  • not in
  • index
  • count

in:如果存在则返回True,否则返回False

list = [1, 2, 3]
# 如果存在则返回True,否则返回False
print(1 in list)
print(4 in list)

image.png not in:如果不存在则返回True,否则返回False

list = [1, 2, 3]
# 如果不存在则返回True,否则返回False
print(1 not in list)
print(4 not in list)

image.png

删除元素

删除列表元素常用的API有如下几个:

  • del
  • pop
  • remove

del:根据下标进行删除

list = [1, 2, 3]
# 根据下标进行删除
del list[1]
print(list)

image.png

pop:删除最后一个元素

list = [1, 2, 3]
# 删除最后一个元素
list.pop()
print(list)

image.png

remove:根据元素的值进行删除

list = [1, 2, 5]
# 根据元素的值进行删除
list.remove(5)
print(list)

image.png

元组

查询元素

元组的元素可直接通过下标来进行查找

tuple = (1, 3, 5)
# 查询元组元素
print(tuple[2])

image.png

有一点需要注意的是元组中的数据是不允许修改的

image.png

当元组只有一个元素时,其类型为int,需要在元素后面加一个逗号

image.png