zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python基础语法-内置函数和模块-常用内置函数(一)

Python基础模块 函数 常用 语法 内置
2023-06-13 09:18:41 时间

Python是一种高级编程语言,拥有许多内置函数和模块,使得开发者能够轻松地完成各种任务。

字符串函数

len()

len()函数返回一个字符串的长度。示例如下:

string = "hello"
print(len(string))

输出:

5

str()

str()函数将一个对象转换为字符串。示例如下:

number = 123
string = str(number)
print(string)

输出:

123

join()

join()函数用于将一个列表或元组中的元素连接成一个字符串。示例如下:

list = ["hello", "world"]
string = " ".join(list)
print(string)

输出:

hello world

split()

split()函数用于将一个字符串按照指定的分隔符分割成一个列表。示例如下:

string = "hello world"
list = string.split(" ")
print(list)

输出:

['hello', 'world']

列表函数

append()

append()函数用于向列表末尾添加一个元素。示例如下:

list = ["hello", "world"]
list.append("!")
print(list)

输出:

['hello', 'world', '!']

pop()

pop()函数用于删除并返回列表中的最后一个元素。示例如下:

list = ["hello", "world", "!"]
element = list.pop()
print(element)
print(list)

输出:

!
['hello', 'world']

sort()

sort()函数用于对列表进行排序。示例如下:

list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
list.sort()
print(list)

输出:

[1, 1, 2, 3, 4, 5, 5, 6, 9]

reverse()

reverse()函数用于将列表倒序排列。示例如下:

list = ["hello", "world", "!"]
list.reverse()
print(list)

输出:

['!', 'world', 'hello']