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

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

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

相关推荐
Andreapiki16 分钟前
风险审计校招技术栈拆解:SQL、Python、Power BI在2026届JD中的真实权重
数据库·python·sql
2601_9669496535 分钟前
股票池发生变化后,如何高效更新行情数据?从全量刷新到增量同步
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
玖石书1 小时前
python-uv-windows环境安装方案
windows·python·uv
happylifetree1 小时前
Python06-08:Python开发工具PyCharm安装
python·pycharm
liuchangng1 小时前
类Jev项目Kev从入门到实战(1):Kev 是什么——不开权重也能自训的决策模型
人工智能·python·jev·kev·决策模型
leihefeng2 小时前
PX06-对比两个 Excel 文件的差异:从逐单元格到生产级实现
python·excel
Ticnix2 小时前
MCP 上个月把自己推翻重写了:Session 没了、Sampling 废了——你学的教程还停在 2025
python·agent·全栈
“AI国潮设计-小江”2 小时前
[AIGC实战] 基于Stable Diffusion的潮汕非遗IP自动化生成工作流(附Python批量处理脚本)
开发语言·人工智能·python·prompt·aigc
LOVE️YOU2 小时前
Python 中的 range 是类还是函数?range 对象该怎么理解?
python
VidDown2 小时前
从视频画面里提取文字:OCR、文字检测与结构化输出
python·网络协议·ocr·音视频·视频编解码·视频