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

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

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

相关推荐
维爱智VR认知学能8 小时前
VR学能软件离线断线与乱序事件测试:确定性到达表与重放
python·单元测试·软件工程·分布式系统·离线同步
郝学胜-神的一滴9 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
Thanks_ks9 小时前
SQL 注入是怎么发生的:从拼接 SQL 讲到预编译语句的防御原理
python·sqlite·orm·占位符·sql 注入·预编译语句·白名单校验
专注仿真13 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体
维爱智VR认知学能13 小时前
VR客户端异常诊断包白名单脱敏与受控字段构建实现
python·单元测试·软件工程·数据安全·日志脱敏
isfox14 小时前
Python 装饰器:别被 @ 符号吓到,它就是个"包装盒"
python
Sakura_j_h_14 小时前
用 uv 搭一个命令行待办工具:pyproject、argparse 与全局安装
python·uv·cli·argparse·pyproject
Wellijohn14 小时前
取 Top-K 别乱用 nlargest:我把 20 万条数据从 k=5 测到 k=199000,发现了三个反直觉的坑
python·算法·性能优化
DanCheng-studio14 小时前
毕设 yolov11血液细胞计数识别系统(源码+论文)
python·毕业设计·毕设
阿enna15 小时前
从误检和漏检出发改进YOLO26n:建立错误样本库
人工智能·python·深度学习·yolo·目标检测·机器学习·cnn