23 Python 字符串常用方法

23 Python 字符串常用方法

在 Python 中,字符串是最常用的数据类型之一。字符串有很多内置的方法,可以帮助我们处理和操作字符串。下面是一些常用的字符串方法及其示例。

1. str.lower()

lower() 方法将字符串中的所有字符转换为小写。

1
2
text = "Hello, World!"
print(text.lower()) # 输出: hello, world!

2. str.upper()

upper() 方法将字符串中的所有字符转换为大写。

1
2
text = "Hello, World!"
print(text.upper()) # 输出: HELLO, WORLD!

3. str.title()

title() 方法将字符串每个单词的首字母转换为大写。

1
2
text = "hello, world!"
print(text.title()) # 输出: Hello, World!

4. str.strip()

strip() 方法用于删除字符串两端的空白字符(包括空格、制表符等)。

1
2
text = "   Hello, World!   "
print(text.strip()) # 输出: Hello, World!

5. str.find()

find() 方法用于查找子字符串在母字符串中的索引。如果子字符串不存在,则返回 -1

1
2
3
4
5
6
text = "Hello, World!"
index = text.find("World")
print(index) # 输出: 7

index_not_found = text.find("Python")
print(index_not_found) # 输出: -1

6. str.replace()

replace() 方法用于替换字符串中的指定子字符串。

1
2
3
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text) # 输出: Hello, Python!

7. str.split()

split() 方法将字符串按照指定的分隔符切割,并返回一个列表。默认的分隔符是空格。

1
2
3
text = "Hello, World! Welcome to Python."
words = text.split()
print(words) # 输出: ['Hello,', 'World!', 'Welcome', 'to', 'Python.']

8. str.join()

join() 方法用于将序列中的字符串连接为一个字符串,使用指定的分隔符。

1
2
3
words = ["Hello", "World", "Python"]
joined_text = " ".join(words)
print(joined_text) # 输出: Hello World Python

9. str.startswith()

startswith() 方法用于判断字符串是否以指定的子字符串开头。

1
2
3
text = "Hello, World!"
print(text.startswith("Hello")) # 输出: True
print(text.startswith("Python")) # 输出: False

10. str.endswith()

endswith() 方法用于判断字符串是否以指定的子字符串结尾。

1
2
3
text = "Hello, World!"
print(text.endswith("World!")) # 输出: True
print(text.endswith("Python")) # 输出: False

11. str.isdigit()

isdigit() 方法用于判断字符串是否只包含数字字符。

1
2
3
4
text1 = "12345"
text2 = "123a5"
print(text1.isdigit()) # 输出: True
print(text2.isdigit()) # 输出: False

12. str.isalpha()

isalpha() 方法用于判断字符串是否只包含字母字符。

1
2
3
4
text1 = "Hello"
text2 = "Hello123"
print(text1.isalpha()) # 输出: True
print(text2.isalpha()) # 输出: False

13. str.isalnum()

isalnum() 方法用于判断字符串是否只包含字母和数字。

1
2
3
4
text1 = "Hello123"
text2 = "Hello 123!"
print(text1.isalnum()) # 输出: True
print(text2.isalnum()) # 输出: False

结论

字符串操作在 Python 编程中非常常见,掌握这些字符串方法将使你的编程能力大大增强。实践是学习的最好方法,建议通过编写小程序来巩固这些字符串方法的使用。

24 使用 `requests` 库进行 API 调用

24 使用 `requests` 库进行 API 调用

在Python的网络编程中,requests 库是一个极为强大且易于使用的工具,它使得与HTTP API的交互变得简单。以下是关于如何使用 requests 库进行API调用的详细小节。

1. 安装 requests

如果你的环境中还没有安装 requests 库,可以通过以下命令进行安装:

1
pip install requests

2. 基本用法

2.1 发送 GET 请求

可以使用 requests.get() 方法来发送一个 GET 请求,下面是一个简单的示例:

1
2
3
4
5
6
7
8
import requests

url = 'https://api.github.com'
response = requests.get(url)

# 打印响应内容和状态码
print('状态码:', response.status_code)
print('响应内容:', response.json())

在这个例子中,我们向 GitHub 的 API 发送了一个 GET 请求,并打印了状态码和响应的 JSON 内容。

2.2 发送 POST 请求

POST 请求通常用于向服务器提交数据。可以使用 requests.post() 方法:

1
2
3
4
5
6
7
8
9
10
11
import requests

url = 'https://httpbin.org/post'
data = {
'name': 'Alice',
'age': 30
}
response = requests.post(url, json=data)

print('状态码:', response.status_code)
print('响应内容:', response.json())

这里我们向 httpbin.org 发送了一个包含个人信息的 POST 请求。

3. 处理请求参数

3.1 查询参数

对于 GET 请求,我们可以通过 params 参数添加查询参数:

1
2
3
4
5
6
7
8
9
url = 'https://api.github.com/search/repositories'
params = {
'q': 'requests',
'sort': 'stars'
}
response = requests.get(url, params=params)

print('状态码:', response.status_code)
print('响应内容:', response.json())

此示例查询了与“requests”相关的 GitHub 仓库,并按照星标数进行排序。

3.2 请求头

有时候,API 需要特定的请求头才能正常工作,我们可以通过 headers 参数来添加请求头:

1
2
3
4
5
6
7
8
url = 'https://api.github.com/user'
headers = {
'Authorization': 'token YOUR_PERSONAL_ACCESS_TOKEN'
}
response = requests.get(url, headers=headers)

print('状态码:', response.status_code)
print('响应内容:', response.json())

在这个例子中,我们使用访问令牌进行了身份验证。

4. 错误处理

当进行 API 调用时,可能会遇到各种错误状况,我们需要优雅地处理这些错误。可以通过检查 response.status_code 来判断请求是否成功:

1
2
3
4
5
6
7
8
response = requests.get('https://api.github.com/user')

if response.status_code == 200:
print('请求成功:', response.json())
elif response.status_code == 404:
print('未找到资源')
else:
print('请求失败,状态码:', response.status_code)

5. 超时设置

在某些情况下,服务器响应可能会很慢,我们可以通过设置超时来避免程序挂起:

1
2
3
4
5
6
7
try:
response = requests.get('https://api.github.com', timeout=5)
print('状态码:', response.status_code)
except requests.exceptions.Timeout:
print('请求超时')
except requests.exceptions.RequestException as e:
print('请求出现错误:', e)

6. 会话对象

使用 requests.Session() 对象可以在多个请求之间保持某些参数,比如 Cookies 或者请求头:

1
2
3
4
5
6
7
8
9
10
session = requests.Session()
session.headers.update({'Authorization': 'token YOUR_PERSONAL_ACCESS_TOKEN'})

# 发起第一个请求
response = session.get('https://api.github.com/user')
print('用户信息:', response.json())

# 可以继续使用同一个 session 进行后续请求
response = session.get('https://api.github.com/users')
print('所有用户:', response.json())

7. 上传文件

requests 也允许很方便地进行文件上传。下面是一个上传文件的示例:

1
2
3
4
5
6
url = 'https://httpbin.org/post'
files = {'file': open('example.txt', 'rb')}
response = requests.post(url, files=files)

print('状态码:', response.status_code)
print('响应内容:', response.json())

8. 总结

通过这一小节,我们了解了如何使用 requests 库进行 API 调用,包括基本的 GET 和 POST 请求、如何处理请求参数、错误处理、超时设置、会话管理以及文件上传。这些知识将帮助我们在实际项目中高效地与各类 API 进行交互。

24 Python 字符串格式化与拼接

24 Python 字符串格式化与拼接

在 Python 中,字符串格式化和拼接是常用的操作。学习这些操作可以帮助你更好地构建字符串,输出信息以及生成动态内容。

字符串拼接

字符串拼接是指将多个字符串合并成一个字符串。Python 中常用的拼接方法有以下几种:

1. 使用 + 运算符

你可以使用 + 运算符将多个字符串拼接在一起:

1
2
3
4
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: Hello World

2. 使用 join() 方法

join() 方法可以将一个可迭代对象(如列表)中的字符串连接起来。你可以使用一个分隔符来连接这些字符串:

1
2
3
words = ["Hello", "World"]
result = " ".join(words)
print(result) # 输出: Hello World

3. 格式化字符串拼接

可以结合字符串格式化方式来拼接字符串,下面会详细介绍。

字符串格式化

字符串格式化是将变量的值嵌入到字符串中的过程。Python 提供了几种不同的字符串格式化方法。

1. 使用 % 操作符

这是一种经典的字符串格式化方法,你可以使用 % 操作符来插入变量:

1
2
3
4
name = "Alice"
age = 30
result = "My name is %s and I am %d years old." % (name, age)
print(result) # 输出: My name is Alice and I am 30 years old.

2. 使用 str.format()

format() 方法是 Python 中一种更现代的字符串格式化方式。它允许将变量插入到字符串中的 {} 占位符中:

1
2
3
4
name = "Bob"
age = 25
result = "My name is {} and I am {} years old.".format(name, age)
print(result) # 输出: My name is Bob and I am 25 years old.

3. 使用 f-string(Python 3.6+)

从 Python 3.6 开始,f-string 提供了一种更简洁的格式化方法。你只需在字符串前加上 f,并在 {} 中直接写变量名:

1
2
3
4
name = "Charlie"
age = 22
result = f"My name is {name} and I am {age} years old."
print(result) # 输出: My name is Charlie and I am 22 years old.

小节总结

  • 字符串拼接可以通过 + 运算符、join() 方法以及格式化字符串的方法来实现。
  • 字符串格式化有多种方式,包括 % 操作符、str.format() 方法和 f-string
  • 了解和掌握这些方法可以帮助你在 Python 编程中更加灵活地处理字符串数据。