Python 常见函数总结
Python 作为一门高级编程语言,内置了许多常见的函数,可以帮助开发者快速实现各种功能。下面是一些常见的Python函数的总结。
数据类型转化函数
int()
int()
函数用于转换其他类型的数据为整型。
a = "123"
b = int(a)
print(b) # 123
str()
str()
函数用于转换其他类型的数据为字符串。
a = 123
b = str(a)
print(b) # "123"
list()
list()
函数用于转换其他类型的数据为列表。
a = "hello"
b = list(a)
print(b) # ['h', 'e', 'l', 'l', 'o']
tuple()
tuple()
函数用于转换其他类型的数据为元组。
a = [1, 2, 3]
b = tuple(a)
print(b) # (1, 2, 3)
字符串操作函数
len()
len()
函数用于获取字符串的长度。
s = "Hello World"
print(len(s)) # 11
upper()
upper()
函数用于将字符串中的小写字母转换为大写字母。
s = "hello world"
print(s.upper()) # "HELLO WORLD"
lower()
lower()
函数用于将字符串中的大写字母转换为小写字母。
s = "HELLO WORLD"
print(s.lower()) # "hello world"
strip()
strip()
函数用于去除字符串开头和结尾的空格。
s = " hello world "
print(s.strip()) # "hello world"
列表操作函数
len()
len()
函数用于获取列表的长度。
l = [1, 2, 3, 4, 5]
print(len(l)) # 5
append()
append()
函数用于在列表末尾添加一个元素。
l = [1, 2, 3]
l.append(4)
print(l) # [1, 2, 3, 4]
pop()
pop()
函数用于将列表末尾的元素弹出。
l = [1, 2, 3, 4]
l.pop()
print(l) # [1, 2, 3]
insert()
insert()
函数用于在指定位置插入一个元素。
l = [1, 2, 3]
l.insert(1, 4)
print(l) # [1, 4, 2, 3]
文件操作函数
open()
open()
函数用于打开一个文件。
f = open("test.txt", "r")
read()
read()
函数用于读取文件中的内容。
f = open("test.txt", "r")
content = f.read()
print(content)
write()
write()
函数用于向文件中写入内容。
f = open("test.txt", "w")
f.write("hello world")
f.close()
以上是Python中一些常见的函数,可以帮助你快速实现各种功能。需要注意的是,使用这些函数时,应该根据具体需求选择合适的函数。同时,我们还要注意异常处理,保证程序的健壮性。