You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:将描述性字符串转为可移植目录名的简洁地道写法

Python 中将描述性字符串转为可移植目录名的地道方案

一、第三方库实现(推荐,标准成熟方案)

使用python-slugify库,它专门处理字符串转可移植标识符的场景,能自动处理大小写、标点、空白字符及各种边缘情况:

  1. 安装库:
pip install python-slugify
  1. 使用示例:
from slugify import slugify

description = "I'm thinking Avocado toast"
dir_name = slugify(description, separator="_")
print(dir_name)  # 输出: im_thinking_avocado_toast

该库还支持处理Unicode字符(比如中文转拼音或保留原字符)、自定义允许的字符等,可通过调整参数适配不同需求。

二、原生Python实现(无依赖)

如果不想引入第三方库,可通过正则表达式和字符串方法实现核心逻辑:

import re

def to_portable_dirname(s):
    # 转为小写
    s = s.lower()
    # 将所有非字母数字的字符替换为下划线
    s = re.sub(r'[^a-z0-9]+', '_', s)
    # 移除首尾的下划线
    s = s.strip('_')
    # 合并连续的下划线为单个
    s = re.sub(r'_+', '_', s)
    return s

# 测试示例
description = "I'm thinking Avocado toast"
print(to_portable_dirname(description))  # 输出: im_thinking_avocado_toast

这个函数会依次完成大小写转换、特殊字符替换、首尾清理和连续下划线合并,覆盖大部分常见场景。

内容的提问来源于stack exchange,提问作者Just Me

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:30:00