python基础07----字符串,列表,元组,字典的公共方法总结

【本章节涵盖内容:公共使用的运算符,python的内置函数】

运算符

运算符 Python 表达式 结果 描述 支持的数据类型
+ [1, 2] + [3, 4] [1, 2, 3, 4] 合并 字符串、列表、元组
* ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 复制 字符串、列表、元组
in 3 in (1, 2, 3) True 元素是否存在 字符串、列表、元组、字典
not in 4 not in (1, 2, 3) True 元素是否不存在 字符串、列表、元组、字典

+

>>> "hello " + "itcast"
'hello itcast'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')

*

>>> 'ab' * 4
'ababab'
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b') * 4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

in

>>> 'itc' in 'hello itcast'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"Delron", "age":24}
True

注意,in在对字典操作时,判断的是字典的键

python内置函数

Python包含了以下内置函数

序号

方法

描述

1

len(item)

计算容器中元素个数

2

del(item)

删除变量

3

max(item)

返回容器中元素最大值

4

min(item)

返回容器中元素最小值

5

range(start, end, step)

生成从start到end的数字,步长为 step,供for循环使用

len

>>> len("hello itcast")
12
>>> len([1, 2, 3, 4])
4
>>> len((3,4))
2
>>> len({"a":1, "b":2})
2

注意:len在操作字典数据时,返回的是键值对个数。

del

del有两种用法,一种是del加空格,另一种是del()

>>> a = 1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = ['a', 'b']
>>> del a[0]
>>> a
['b']
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

max

>>> max("hello itcast")
't'
>>> max([1,4,522,3,4])
522
>>> max({"a":1, "b":2})
'b'
>>> max({"a":10, "b":2})
'b'
>>> max({"c":10, "b":2})
'c'

range

>>> range(2, 10, 3)
[2, 5, 8]
>>> for x in range(2, 10, 3):
...     print(x)
...
2
5
8

注意:range 可以生成数字供 for 循环遍历。三个数字分别为 起始、结束、步长

猜你喜欢

转载自blog.csdn.net/qq_36622490/article/details/86522372