一天学会三个实用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写得好------目标清晰、分步骤、约束返回格式,模型给的结果直接就能用,连解析都不用愁!

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

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

相关推荐
Larcher1 小时前
Python List、切片与大模型:从入门到实践的优雅之旅
python·ai编程
用户6337197359011 小时前
_winapi.CreateProcess....FileNotFoundError: [WinError 2] 系统找不到指定的文件
python
清水白石0081 小时前
Python 数据建模指南:dataclass、TypedDict 与 Pydantic 的选型博弈
前端·javascript·python
小郑加油1 小时前
python_综合训练
开发语言·python
葬送的代码人生1 小时前
Notebook环境下的List、Slice与LLM大冒险
python·jupyter·api
多彩电脑1 小时前
Kivy的事件向方法传递的event是什么?
开发语言·python
hnxaoli1 小时前
统信小程序(十四)支持拖拽的旋图程序
python·小程序
小林ixn1 小时前
从 List 切片到 LLM 调用:一篇搞定 Python 基础与 AI 接口
python·ai编程
sugar__salt1 小时前
从Python列表切片到LLM接口实战:零基础AI编程落地教程
开发语言·python·ai·prompt·transformer·ai编程