欢迎访问宙启技术站
智能推送

Python内置函数的使用方法和示例代码

发布时间:2023-06-22 00:27:11

Python有很多内置函数,这些函数是在Python解释器中一开始就定义好的,可以直接使用,不需要导入任何模块。这些内置函数大多数是处理字符串、列表、字典、数学运算等等常用操作。下面列出了一些常用的内置函数及其使用方法和示例代码。

1. print()

print()函数是Python内置的输出函数,可以将内容输出到控制台。

例子:

print("Hello,World!")

输出:

Hello,World!

2. len()

len()函数用来获取字符串、列表、元组、字典等容器类型的长度。

例子:

str = "Hello,World!"
print(len(str))

输出:

12

3. type()

type()函数返回变量的类型。

例子:

str = "Hello,World!"
print(type(str))

输出:

<class 'str'>

4. int()

int()函数可以将一个字符串类型的数字转换成整型。

例子:

num = "123"
print(int(num))

输出:

123

5. float()

float()函数可以将一个字符串类型的数字转换成浮点型。

例子:

num = "3.14"
print(float(num))

输出:

3.14

6. str()

str()函数将一个对象转换成字符串类型。

例子:

num = 123
print(str(num))

输出:

123

7. list()

list()函数可以将一个可迭代对象转换成列表类型。

例子:

str = "Hello,World!"
print(list(str))

输出:

['H', 'e', 'l', 'l', 'o', ',', 'W', 'o', 'r', 'l', 'd', '!']

8. tuple()

tuple()函数可以将一个可迭代对象转换成元组类型。

例子:

str = "Hello,World!"
print(tuple(str))

输出:

('H', 'e', 'l', 'l', 'o', ',', 'W', 'o', 'r', 'l', 'd', '!')

9. dict()

dict()函数可以将一个包含键值对的可迭代对象转换成字典类型。

例子:

lst1 = ["A", "B", "C"]
lst2 = [1, 2, 3]
print(dict(zip(lst1, lst2)))

输出:

{'A': 1, 'B': 2, 'C': 3}

10. sorted()

sorted()函数可以对可迭代对象进行排序,返回一个排序后的新列表。

例子:

lst = [3, 2, 1, 4]
print(sorted(lst))

输出:

[1, 2, 3, 4]

11. sum()

sum()函数可以对可迭代对象进行求和操作。

例子:

lst = [1, 2, 3, 4, 5]
print(sum(lst))

输出:

15

12. max()

max()函数可以获取可迭代对象中的最大值。

例子:

lst = [1, 2, 3, 4, 5]
print(max(lst))

输出:

5

13. min()

min()函数可以获取可迭代对象中的最小值。

例子:

lst = [1, 2, 3, 4, 5]
print(min(lst))

输出:

1

14. all()

all()函数可以判断可迭代对象中的元素是否全部为True。

例子:

lst = [True, False, True]
print(all(lst))

输出:

False

15. any()

any()函数可以判断可迭代对象中是否有任意一个元素为True。

例子:

lst = [True, False, True]
print(any(lst))

输出:

True

以上是常用的一些内置函数,使用方法和示例代码,希望对大家有所帮助。