【Python基础】详解Python基础函数,包教包会(上)
运行环境
python:3.8.3
jupyter-notebook : 6.4.0
注意:本文案例可以直接在 jupyter-notebook 上运行,但在 PyCharm 上的话需要代码的最后一句加上 print 哦!
输入输出函数
print()
print() 无疑是我们使用最多的函数,他可以直接输出、指定间隔/结尾字符、将输出内容保存到指定文件(应用:记录自动化脚本异常信息)等。下面列举它的常见用法。
:one: 直接输出
print('hello world')
| output:hello world |
|---|
:two: 指定间隔字符sep
print('A', 'B', 'C', sep=' Python ')
| output:A Python B Python C |
|---|
:three: 指定结尾字符
print('hello', 'world', end='Python')
| output:hello worldPython |
|---|
:four: 将输出内容保存到outfile.txt文件中
print('hello', 'world', sep=' ', file=open('outfile.txt', 'w', encoding='utf-8'))
input()
input() 可以接收用户输入的内容,并以字符串的形式保存。
name = input('name:')

在 jupyter notebook 上执行的效果可能和别的编辑器不同,但操作都是输入完后,按 “回车” 即可。
获取数据类型
type()
type() 返回指定值的数据类型。
type([1, 2])
| output:list |
|---|
isintance()
isintance() 判断传入的值是否为指定类型,返回 True/False 。
isinstance('Python新视野', str)
| output:True |
|---|
字符串操作
str()
str() 将指定值转为字符串类型。
str(1.23)
| output:‘1.23’ |
|---|
eval()
eval() 将字符串转成有效的表达式来求值或者计算结果。可以将字符串转化成列表(list),元组(tuple),字典(dict),集合(set)等。
res = eval("{'name': 'Python'}")
type(res)
| output:dict |
|---|
str.capitalize()
capitalize() 返回字符串中的首字母大写,其余小写的字符串
cap_str = 'python新视野'.capitalize()
cap_str
| output:‘Python新视野’ |
|---|
str.center()
center() 返回一个指定宽度的居中字符串,左右部分空余部分用指定字符填充。
width:长度fillchar:空余部分填充的字符,默认使用空格
center_str = 'Python新视野'.center(15, "!")
center_str
| output:’!!!Python新视野!!!’ |
|---|
str.count()
str.count(sub, start, end) 返回 sub 在 str 中出现的次数,可以通过 [start, end] 指定范围,若不指定,则默认查找整个字符串。
- sub: 子串
- start: 开始的索引,默认为 0
- end: 结束的索引,默认为字符串的长度
name = 'python python'
# 第一次按默认范围统计'p'出现的次数,
# 第二次指定start=1,即从第二个字符开始统计。
name.count('p'), name.count('p', 1)
| output:(2, 1) |
|---|
str.find() & str.rfind()
:one: find() 从左往右扫描字符串,返回 sub 第一次出现的下标。可以通过 [start, end] 指定范围,若不指定,则默认查找整个字符串。如最后未找到字符串则返回 -1。
- sub: 子串
- start: 开始检索的位置,默认为 0
- end: 结束检索的位置,默认为字符串的长度
name = 'Python'
# 第一次按默认范围查找'Py'第一次出现的下标
# 第二次指定start=1,即从第二个字符开始查找。
name.find('Py'), name.find('Py', 1)
| output:(0, -1) |
|---|
:two: rfind 与 find() 的用法相似,只是从右往左开始扫描,即从字符串末尾向字符串首部扫描。
name = 'Python'
name.rfind('Py'), name.rfind('Py', 1)
| output:(0, -1) |
|---|
str.index() & str.rindex()
:one: index() 和 find() 用法相同,唯一的不同是如果找不到 sub 会报错。
示例 :a:
name = 'Python'
name.index('Py', 0)
| output:0 |
|---|
示例 :b:
name = 'Python'
name.index('Py', 1)
| output:ValueError: substring not found |
|---|
:two: rindex() 和 index() 用法相同,不过是从右边开始查,它的查询与 index() 相同。
name = 'Python'
name.rindex('Py', 0)
| output:0 |
|---|
str.isalnum()
isalnum() 判断字符串中是否所有字符都是字母(可以为汉字)或数字,是 True ,否 False,空字符串返回 False。
示例 :a:
'Python新视野'.isalnum()
| output:True |
|---|
示例 :b:
'Python-sun'.isalnum()
| output:False |
|---|
'-' 是符号,所以返回 False。
str.isalpha()
isalpha() 判断字符串中是否所有字符都是字母(可以为汉字),是 True ,否 False,空字符串返回 False。
示例 :a:
'Python新视野'.isalpha()
| output:True |
|---|
示例 :b:
'123Python'.isalpha()
| output:False |
|---|
其中包含了数字,返回 False
str.isdigit()
isdigit() 判断字符串中是否所有字符都是数字(Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字),是 True ,否 False,空字符串返回 False。
示例 :a:
'四123'.isdigit()
| output:False |
|---|
其中包含了汉字数字,返回 False
示例 :b:
b'123'.isdigit()
| output:True |
|---|
byte 数字返回 True 。
str.isspace()
字符串中只包含空格(\n、\r、\f、\t、\v),是 True ,否 False,空字符串返回 False。
| 符号 | 含义 |
|---|---|
| \n | 换行 |
| \r | 回车 |
| \f | 换页 |
| \t | 横向制表符 |
| \v | 纵向制表符 |
' \n\r\f\t\v'.isspace()
| output:True |
|---|
str.join()
join(iterable) 以指定字符串作为分隔符,将 iterable 中所有的元素(必须是字符串)合并为一个新的字符串。
','.join(['Python', 'Java', 'C'])
| output:‘Python,Java,C’ |
|---|
str.ljust() & str.rjust()
:one: ljust() 返回一个指定宽度左对齐的字符串
width:长度fillchar:右部空余部分填充的字符,默认使用空格
ljust_str = 'Python新视野'.ljust(15, "!")
ljust_str
| output:‘Python新视野!!!!!!’ |
|---|
:two: rjust() 返回一个指定宽度右对齐的字符串,与 ljust 操作正好相反。
width:长度fillchar:左部空余部分填充的字符,默认使用空格
rjust_str = 'Python新视野'.rjust(15, "!")
rjust_str
| output:’!!!!!!Python新视野’ |
|---|
str.lower() & str.islower()
:one: lower() 将指定字符串转换为小写。
lower_str = 'Python新视野'.lower()
lower_str
| output:‘python新视野’ |
|---|
:two: islower() 判断字符串所有区分大小写的字符是否都是小写形式,是 True ,否 False,空字符串或字符串中没有区分大小写的字符返回 False 。
'python-sun'.islower()
| output:True |
|---|
'python-sun' 区分大小写的字符有 'pythonsun',并且都是小写,所以返回 True 。
str.lstrip() & str.rstrip() & str.strip()
:one: lstrip() 会在字符串左侧根据指定的字符进行截取,若未指定默认截取左侧空余(空格,\r,\n,\t等)部分。
name = '+++Python新视野+++'
name.lstrip('+')
| output:‘Python新视野+++’ |
|---|
:two: rstrip() 与 lstrip() 用法相似,只是截取右侧的内容。
name = '+++Python新视野+++'
name.rstrip('+')
| output:’+++Python新视野’ |
|---|
:three: strip() 实际是 lstrip() 与 rstrip() 的结合,它会截取字符串两边指定的字符。
name = '+++Python新视野+++'
name.strip('+')
| output:‘Python新视野’ |
|---|
str.split() & str.splitlines()
:one: str.split(sep=None, maxsplit=-1) 使用 sep 作为分隔符将字符串进行分割,返回字符串中的单词列表。
- seq: 用来分割字符串的分隔符。
None(默认值)表示根据任何空格进行分割,返回结果中不包含空格。 - maxsplit: 指定最大分割次数。-1(默认值)表示不限制。
split_str = 'P y t h o n 新 视 野'
split_str.split(maxsplit=2)
| output:[‘P’, ‘y’, ‘t h o n 新 视 野’] |
|---|
使用默认的空格进行分割,设置最大的分割次数为2
:two: str.splitlines 返回字符串中的行列表,它按照行 ('\r',\n','\r\n') 分隔,返回分隔后的列表。它只有一个参数 keepends 表示是否在结果中保留换行符,False (默认)不保留,True 保留。
示例 :a:
split_str = 'P\ny\r t h o n 新 视 野'
split_str.splitlines()
| output:[‘P’, ‘y’, ’ t h o n 新 视 野’] |
|---|
示例 :b:
split_str = 'P\ny\r t h o n 新 视 野'
split_str.splitlines(keepends=True)
| output:[‘P\n’, ‘y\r’, ’ t h o n 新 视 野’] |
|---|
str.startswith() & str.endswith
:one: startswith(prefix[, start[, end]]) 检查字符串是否是以指定子字符串 substr 开头,是 True ,否 False,空字符串会报错。如果指定 start 和 end ,则在指定范围内检查。
startswith_str = 'Python新视野'
startswith_str.startswith('thon', 2)
| output:True |
|---|
从第 3 个字符开始检测
:two: str.endswith(suffix[, start[, end]]) 与 startswith 用法相同,不同之处是检查字符串是否以指定子字符串结尾,是 True ,否 False,空字符串会报错。
endswith_str = 'Python新视野'
endswith_str.endswith('thon', 0, 6)
| output:True |
|---|
从第 1 个字符开始检测,到第 7 个字符结束(不包含第 7 个),注意这里的范围和字符串切片其实是一样的道理,都是前闭后开。
str.title() & str.istitle()
:one: title() 返回字符串中每一个单词首字母大写。
title_str = 'python新视野 python新视野'.title()
title_str
| output:‘Python新视野 Python新视野’ |
|---|
:two: istitle() 判断字符串是否满足每一个单词首字母大写,是 True ,否 False,空字符串返回 False。
'Abc Def '.istitle()
| output:True |
|---|
str.upper() & str.isupper()
:one: upper() 将指定字符串中字母转换为大写。
upper_str = 'Python新视野'.upper()
upper_str
| output:‘PYTHON新视野’ |
|---|
:two: isupper() 判断字符串所有区分大小写的字符是否都是大写形式,是 True ,否 False,空字符串或字符串中没有区分大小写的字符返回 False 。
'PYTHON-SUN'.isupper()
| output:True |
|---|
列表操作
list()
list() 将可迭代对象转成列表。
示例 :a:
list((0,1,2)) + list({0,1,2}) + list('012')
| output:[0, 1, 2, 0, 1, 2, ‘0’, ‘1’, ‘2’] |
|---|
将元组、集合、字符串转换成列表并通过运算符连接。
示例 :b:
list(range(3))
| output:[0, 1, 2] |
|---|
将可迭代对象转换成列表
list.append()
lst = ['Python', 'Java']
lst.append('C')
lst
| output:[‘Python’, ‘Java’, ‘C’] |
|---|
list.extend()
extend() 在列表的末尾添加可迭代对象(列表、元组、字典、字符串)中的元素来扩展列表。
:one: 追加列表
lst = ['Python', 'Java', 'C']
lst.extend([1, 2, 3])
lst
| output:[‘Python’, ‘Java’, ‘C’, 1, 2, 3] |
|---|
:two: 追加字符串
lst = ['Python', 'Java', 'C']
lst.extend('123')
lst
| output:[‘Python’, ‘Java’, ‘C’, ‘1’, ‘2’, ‘3’] |
|---|
将字符串中的每一个字符当做一个元素追加到原列表末尾
:three: 追加集合
lst = ['Python', 'Java', 'C']
lst.extend({1,2,3})
lst
| output:[‘Python’, ‘Java’, ‘C’, 1, 2, 3] |
|---|
:four: 追加字典
lst = ['Python', 'Java', 'C']
lst.extend({1: 'b', 2: 'a'})
lst
| output:[‘Python’, ‘Java’, ‘C’, 1, 2] |
|---|
只将字典的 key 值追加到原列表末尾
list.insert()
insert(index, object) 将指定对象插入到列表的 index 位置,原本 index 位置上及 > index 的元素的元素整体后移。
示例 :a:
lst = ['Python', 'Java', 'C']
lst.insert(1, 'C++')
lst
| output:[‘Python’, ‘C++’, ‘Java’, ‘C’] |
|---|
示例 :b:
lst = ['Python', 'Java', 'C']
lst.insert(6, 'C++')
lst
| output:[‘Python’, ‘Java’, ‘C’, ‘C++’] |
|---|
当 index 的值大于列表长度时,会在列表末尾添加。
list.pop()
pop(index=-1) 移除列表中指定位置元素(默认最后一个),并且返回移除元素的值。若指定的 index 值超过列表长度则会报错。
lst = ['Python', 'Java', 'C']
lst.pop(1), lst
| output:(‘Java’, [‘Python’, ‘C’]) |
|---|
list.remove(元素)
lst.remove(value) 移除列表中第一次出现的 value ,无返回值,直接修改列表;如果 value 不在列表中则报错。
示例 :a:
lst = ['Python', 'Java', 'C', 'Python']
lst.remove('Python')
lst
| output:[‘Java’, ‘C’, ‘Python’] |
|---|
只删除了第一次出现的 Python
示例 :b:
lst = ['Python', 'Java', 'C', 'Python']
lst.remove('HTML')
lst
| output:ValueError: list.remove(x): x not in list |
|---|
HTML 不在列表中,发生错误
list.clear()
list.clear() 移除列表中所有的元素,无返回值。
lst = ['Python', 'Java', 'C']
lst.clear()
lst
| output:[] |
|---|
list.index()
index(value, start, stop) 返回列表中查找的第一个与value匹配的元素下标,可通过 [start, stop) 指定查找范围。
示例 :a:
lst = ['Python', 'Java', 'C',
'Python', 'Python']
lst.index('Python')
| output:0 |
|---|
不指定范围,在列表全部元素中查找
示例 :b:
lst = ['Python', 'Java', 'C',
'Python', 'Python']
lst.index('Python', 1, 3)
| output:ValueError: ‘Python’ is not in list |
|---|
指定范围 [1, 3) ,即在[‘Java’, ‘C’]中查找 Python 很明显不存在,发生报错
list.count()
count(value) 返回 value 在列表中出现的次数。若未在列表中找到 value 则返回 0 。
示例 :a:
lst = ['Python', 'Java', 'C',
'Python', 'Python']
lst.count('Python')
| output:3 |
|---|
示例 :b:
lst = ['Python', 'Java', 'C',
'Python', 'Python']
lst.count('Py')
| output:0 |
|---|
列表中无元素 'Py',返回 0 。
list.reverse()
reverse() 将列表逆序排列,无返回值。
lst = [1, 5, 9, 2]
lst.reverse()
lst
| output:[2, 9, 5, 1] |
|---|
list.sort()
sort() 对列表进行指定方式的排序,修改原列表,该排序是稳定的(即两个相等元素的顺序不会因为排序而改变)。
- key: 指定可迭代对象中的每一个元素来按照该函数进行排序
- reverse:
False为升序,True为降序。
示例 :a:
lst = [1, 5, 9, 2]
lst.sort()
lst
| output:[1, 2, 5, 9] |
|---|
示例 :b:
lst = ['Python', 'C', 'Java']
lst.sort(key=lambda x:len(x), reverse=False)
lst
| output:[‘C’, ‘Java’, ‘Python’] |
|---|
指定 key 计算列表中每个元素的长度,并按照长度进行升序排序
list.copy()
copy() 对列表进行拷贝,返回新生成的列表,这里的拷贝是浅拷贝,下面会说明为什么特意说它是浅拷贝。
示例 :a:
lst = [[1,2,3], 'a' ,'b']
lst_copy = lst.copy()
lst_copy.pop()
lst, lst_copy
| output:([[1, 2, 3], ‘a’, ‘b’], [[1, 2, 3], ‘a’]) |
|---|
对 lst 进行 copy ,然后删除列表 lst_copy 的最后一个元素,此时的 lst 的最后一个元素并未被删除,说明两个列表指向的地址确实不一样。
示例 :b:
lst = [[1,2,3], 'a' ,'b']
lst_copy = lst.copy()
lst_copy[0].pop()
lst_copy.pop()
lst, lst_copy
| output:([[1, 2], ‘a’, ‘b’], [[1, 2], ‘a’, ‘b’]) |
|---|
这里执行和上一个示例一样的操作,只是这次再删除一个数据,即列表嵌套的子列表中最后一个元素,观察结果,发现这时不仅仅是 lst_copy 的列表发生改变,原列表 lst 中嵌套的字列表也发生了改变。说明两个列表指向的地址不一样,但子列表中指向的地址是相同的。
扩展:直接赋值、浅拷贝、深拷贝
(1)直接赋值,传递对象的引用而已。原始列表改变,被赋值的对象也会做相同改变。
(2)浅拷贝,没有拷贝子对象,所以原始数据子对象改变,拷贝的子对象也会发生变化。
(3)深拷贝,包含对象里面的子对象的拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变,二者完全独立。
:one: 先看直接赋值
lst = [1,2,3,[1,2]]
list1 = lst
# --直接赋值--
lst.append('a')
list1[3].append('b')
print(lst,'地址:',id(lst))
print(list1,'地址:',id(list1))
# [1, 2, 3, [1, 2, 'b'], 'a'] 地址: 2112498512768
# [1, 2, 3, [1, 2, 'b'], 'a'] 地址: 2112498512768
无论 lst 还是 list1 发生改变,二者都会受到影响。
:two: 浅拷贝需要用到 copy 模块,或者用 list.copy() 效果一样
from copy import copy
lst = [1, 2, 3, [1, 2]]
list2 = copy(lst)
# --浅拷贝--
lst.append('a')
list2[3].append('b')
print(lst,'地址:',id(lst))
print(list2,'地址:',id(list2))
# [1, 2, 3, [1, 2, 'b'], 'a'] 地址: 2112501949184
# [1, 2, 3, [1, 2, 'b']] 地址: 2112495897728
lst 与 list2 地址不同,但子列表的地址仍是相同的,修改子列表中的元素时,二者都会受到影响。
:three: 深拷贝需要用到 copy 模块中的 deepcopy ,此时两个列表完全独立。
from copy import deepcopy
lst = [1, 2, 3, [1, 2]]
list3 = deepcopy(lst)
# --深拷贝--
lst.append('a')
list3[3].append('b')
print(lst,'地址:',id(lst))
print(list3,'地址:',id(list3))
# [1, 2, 3, [1, 2], 'a'] 地址: 2112506144192
# [1, 2, 3, [1, 2, 'b']] 地址: 2112499460224
根据结果可以看到修改子列表中的值时,原列表未发生改变。
下篇讲解元组、字典、集合,有兴趣的可以关注一下哦~
- 点赞
- 收藏
- 关注作者
评论(0)