一天学会三个实用Python技巧:切片、strip()和LLM接口调用

从基础到AI,一篇讲清楚最实用的知识点


前言

最近在学习Python,发现有几个知识点既基础又实用,分享给大家。


一、Python List:比数组更灵活

Python中最常用的是List,不是数组。List的特点:

  • 动态大小:不用提前指定容量
  • 类型灵活:可以混放不同类型的数据

python

ini 复制代码
# 创建一个List
L = ["张三", "李四", "王五", "赵六", "钱七"]

# 访问元素
print(L[0])  # 张三
print(L[1])  # 李四

二、切片操作:一行代码搞定批量取值

切片是Python最实用的特性之一,语法:[start:end:step]

基础切片

python

scss 复制代码
L = ["张三", "李四", "王五", "赵六", "钱七"]

# 取前3个
print(L[0:3])  # ['张三', '李四', '王五']
print(L[:3])   # 省略开头,效果相同

# 取中间
print(L[1:3])  # ['李四', '王五']

# 取倒数2个
print(L[-2:])  # ['赵六', '钱七']

带步长的切片

python

ini 复制代码
# 生成0-99的列表
numbers = list(range(100))

print(numbers[:10])      # 前10个
print(numbers[-10:])     # 后10个
print(numbers[:10:2])    # 前10个,每隔1个取1个
print(numbers[::5])      # 每5个取1个
# 输出:[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, ...]

三、strip()方法:去除字符串首尾空白

基础用法

python

bash 复制代码
# 直接使用strip()
text = "   hello world   "
print(text.strip())  # "hello world"

# 字符串也支持切片
print('ABCDEFG'[:3])   # "ABC"
print('ABCDEFG'[::2])  # "ACEG"

手写strip()理解原理(双指针+切片)

python

sql 复制代码
def my_trim(s):
    left = 0
    right = len(s)
    
    # 左指针跳过开头空格
    while left < right and s[left] == ' ':
        left += 1
    
    # 右指针跳过结尾空格
    while right > left and s[right - 1] == ' ':
        right -= 1
    
    # 切片截取
    return s[left:right]

print(my_trim("   hello world "))  # "hello world"

strip()家族

方法 作用 示例
strip() 去除两端空白 " a ".strip()"a"
lstrip() 去除左端空白 " a ".lstrip()"a "
rstrip() 去除右端空白 " a ".rstrip()" a"

四、LLM接口调用:5分钟接入AI能力

背景知识

  • Transformer:Google开源的架构,是当前所有大语言模型的基础
  • 兼容性:DeepSeek、通义千问等国内模型都兼容OpenAI接口

代码实战:用Python调用LLM生成产品文案

下面是一个完整的实战示例,展示如何用Python调用LLM接口,为产品生成符合要求的文案。

写好Prompt的三个要点

  1. 清晰表达目标:说清楚要做什么
  2. 分步骤:用1、2、3引导模型思考
  3. 约束格式:要求返回JSON,便于解析

完整代码

ini 复制代码
from openai import OpenAI

# 初始化客户端
client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.deepseek.com/v1"  # 以DeepSeek为例
)

def get_response(prompt):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content
prompt = """
Consideration product: 工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具

1. Compose human readable product title used on Amazon in english within 20 words.
2. Write 5 selling points for the products in Amazon
3. Evaluate a price range for this product in U.S.

Output the result in json format with three properties called title, selling_points and price_range
"""

result = get_response(prompt)
print(result)

返回结果:

json

bash 复制代码
{
  "title": "Inflatable PVC Glow Frog Toy for Night Market, Water Play, and Kids' Outdoor Fun",
  "selling_points": [
    "Bright LED glowing design attracts attention at night, perfect for night markets and evening beach parties.",
    "Made from durable, non-toxic PVC material safe for children and resistant to punctures during water play.",
    "Lightweight and easy to inflate/deflate for convenient storage and portability to pools, lakes, or backyards.",
    "Versatile toy suitable for both land and water use, including bath time, swimming pools, and outdoor play.",
    "Fun frog shape with vibrant colors enhances imaginative play and encourages active outdoor entertainment for kids."
  ],
  "price_range": "$9.99 -- $14.99"
}

五、总结

知识点 核心要点 一句话总结
List 动态、灵活、无类型限制 Python最常用的容器
切片 [start:end:step] 一行代码批量取数据
strip() 去除首尾空白 字符串清洗利器
LLM调用 兼容OpenAI接口 写好Prompt是关键

个人感想:

说实话,今天这一套学下来,最大的感受就是------Python的切片太实用了!

以前要取数组某一段,要么写循环要么写好几行,现在一行[:3]或者[-2:]就搞定,代码瞬间清爽了不少,而且字符串也能用同样的语法,统一又方便。

另一个感触是,LLM接口比想象中简单太多。不要把AI开发想的太高深了,相信只要认真学习,你会有所造诣的!而且只要prompt写得好------目标清晰、分步骤、约束返回格式,模型给的结果直接就能用,连解析都不用愁!

能偷懒的时候别硬写,但偷懒之前最好知道它为什么能跑。

希望这篇对你有帮助,欢迎交流讨论!🚀

相关推荐
江华森1 小时前
Python 实现 2048 游戏(三):面向对象重构与AI模拟
python
可以飞的话2 小时前
五、数据处理1
python
鱼毓屿御2 小时前
Python 装饰器与函数调用机制(复习笔记 · 2026-07-07)
开发语言·python
AC赳赳老秦2 小时前
采购专员自动化:OpenClaw 自动比价、生成询价单、跟踪供应商报价进度实战指南
开发语言·数据库·人工智能·python·自动化·github·openclaw
ednO8nqdR2 小时前
Python小游戏制作:如何实现可配置的跨分辨率界面布局
python·plotly·django·virtualenv·scikit-learn·fastapi·pygame
林泽毅2 小时前
Qwen3.5 DPO 模型对齐实战(pytrio训练版)
人工智能·python·算法
荣码3 小时前
LangGraph多步工作流:Agent不够用的时候,我踩了4个坑
java·python
曲幽3 小时前
从卡顿到丝滑:FastAPI 调用外部 API 的正确姿势(httpx 实战)
python·fastapi·web·async·httpx·client·await·requests·aiohttp
不瘦80斤不改名3 小时前
HalfCart:基于LBS的1\.5km本地拼单系统全栈实践与踩坑复盘
python·docker·typescript·pycharm
深盾科技_Virbox3 小时前
软件交付保护如何从加壳走向代码虚拟化
java·python·安全