平常用的多的函数有哪些
时间: 2024-03-05 09:51:05 浏览: 18
以下是平常使用较多的 Python 函数:
### 1. `print()`
用于输出文本或变量的值到控制台,方便调试。
```python
print("hello world")
```
### 2. `input()`
用于获取用户输入的值,可以通过提示语句向用户说明输入的内容。
```python
name = input("请输您的名字:")
```
### 3. `len()`
用于获取字符串、列表、元组等对象的长度。
```python
lst = [1, 2, 3]
print(len(lst)) # 3
```
### 4. `range()`
用于生成一个整数序列,常用于循环中。
```python
for i in range(10):
print(i)
```
### 5. `open()`
用于打开一个文件,并返回文件对象。
```python
f = open("test.txt", "r")
```
### 6. `str()`
用于将其他类型的对象转换为字符串类型。
```python
num = 123
s = str(num)
```
### 7. `int()`
用于将字符串或浮点数类型的对象转换为整数类型。
```python
s = "123"
num = int(s)
```
### 8. `float()`
用于将字符串或整数类型的对象转换为浮点数类型。
```python
s = "3.14"
num = float(s)
```
### 9. `join()`
用于将字符串列表中的所有字符串以指定的分隔符连接起来。
```python
lst = ["hello", "world"]
s = "-".join(lst)
```
### 10. `split()`
用于将一个字符串以指定的分隔符分割成多个子字符串,并返回一个列表。
```python
s = "hello-world"
lst = s.split("-")
```
### 11. `strip()`
用于去除字符串两端的空格或指定的字符。
```python
s = " hello "
s = s.strip()
```
### 12. `replace()`
用于将字符串中指定的子字符串替换为另一个子字符串。
```python
s = "hello world"
s = s.replace("world", "python")
```
### 13. `format()`
用于格式化输出字符串,常用于字符串拼接中。
```python
name = "Tom"
age = 18
s = "My name is {}, and I'm {} years old.".format(name, age)
```
以上是平常使用较多的 Python 函数,掌握它们可以帮助我们更高效地编写代码。