一天学会三个实用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 学习第 53 天】列表基础
python·学习笔记·编程入门
Dumbness1 小时前
群里 @ 机器人发"查订单",指令一条都没命中:微信群机器人在路由前漏掉的几步归一化
python·微信
用户1614840955452 小时前
用 M4 Pro 跑羽毛球视频 AI 分析(二):TrackNet MPS 加速 3.2 倍、卡尔曼滤波补漏与自动回合剪辑
python
用户4019925568612 小时前
基于对话树回溯的社媒评论流买方意图识别与噪音过滤实践
python
用户0332126663672 小时前
使用 Python 加密或解密 PDF 文档
python
小七-七牛开发者3 小时前
让 Go 走得更远:用 LLGo 打通 Go 与 C/C++/Python 生态
python·编程·编译器·llvm·llgo
CyrusYiVPP4 小时前
实测 Ollama 本地部署:我用 Python 搓了个离线问答机器人,Qwen4 27B 一到换个模型名就能用
人工智能·python
2601_967980114 小时前
Python中flatten( )函数及函数用法详解
python·numpy·数组操作·flatten函数·列表处理
xbzb4 小时前
自定义 yum 软件源:Linux 上 createrepo,Windows 上纯 Python 也能造
linux·运维·windows·python·yum·createrepo
合尘猫8 小时前
图片表格变结构化数据:OCR 后的三个坑
python·ocr