Python中常见的内建方法(built-inmethod)介绍
发布时间:2024-01-16 15:37:13
Python中常见的内建方法有很多,包括类型转换、字符串处理、列表操作、字典操作、文件操作、数学运算等等。以下是一些常见的内建方法及其使用例子。
1. 类型转换:
- int():将给定的参数转换为整数类型。
num_str = "123" num = int(num_str) print(num) # 输出 123
- float():将给定的参数转换为浮点数类型。
num_str = "3.14" num = float(num_str) print(num) # 输出 3.14
- str():将给定的参数转换为字符串类型。
num = 123 num_str = str(num) print(num_str) # 输出 "123"
2. 字符串处理:
- len():返回给定字符串的长度。
text = "Hello, world!" length = len(text) print(length) # 输出 13
- lower():将字符串中的所有字符转换为小写。
text = "HELLO" lower_text = text.lower() print(lower_text) # 输出 "hello"
- upper():将字符串中的所有字符转换为大写。
text = "hello" upper_text = text.upper() print(upper_text) # 输出 "HELLO"
- replace():将字符串中的指定子字符串替换为另一个子字符串。
text = "Hello, world!"
new_text = text.replace("world", "Python")
print(new_text) # 输出 "Hello, Python!"
3. 列表操作:
- append():向列表末尾添加一个元素。
numbers = [1, 2, 3] numbers.append(4) print(numbers) # 输出 [1, 2, 3, 4]
- remove():从列表中移除指定元素。
numbers = [1, 2, 3, 4] numbers.remove(3) print(numbers) # 输出 [1, 2, 4]
- sort():对列表进行升序排序。
numbers = [3, 1, 4, 2] numbers.sort() print(numbers) # 输出 [1, 2, 3, 4]
4. 字典操作:
- keys():返回字典中所有键的列表。
student = {"name": "Alice", "age": 18, "grade": "A"}
keys = student.keys()
print(keys) # 输出 ["name", "age", "grade"]
- values():返回字典中所有值的列表。
student = {"name": "Alice", "age": 18, "grade": "A"}
values = student.values()
print(values) # 输出 ["Alice", 18, "A"]
- items():返回字典中所有键值对的列表。
student = {"name": "Alice", "age": 18, "grade": "A"}
items = student.items()
print(items) # 输出 [("name", "Alice"), ("age", 18), ("grade", "A")]
5. 文件操作:
- open():打开文件并返回文件对象。
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
- write():将指定内容写入文件。
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
- readline():读取文件的下一行内容。
file = open("example.txt", "r")
line1 = file.readline()
line2 = file.readline()
print(line1) # 输出 "Hello, world!
"
print(line2) # 输出 ""
file.close()
6. 数学运算:
- abs():返回给定数的绝对值。
num = -5 abs_num = abs(num) print(abs_num) # 输出 5
- max():返回给定数中的最大值。
numbers = [5, 2, 9, 1] max_num = max(numbers) print(max_num) # 输出 9
- min():返回给定数中的最小值。
numbers = [5, 2, 9, 1] min_num = min(numbers) print(min_num) # 输出 1
以上只是一小部分常见的内建方法,Python还有很多其他有用的内建方法可以帮助我们更好地完成任务。对于每个内建方法,我们可以通过查阅Python官方文档来了解更多信息。
