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

如何修改Python代码处理split('.')的各类错误场景?

解决方案

以下是修改后的代码,可正确处理所有指定的错误场景:

def filesplitter_to_list(name: str) -> list:
    # 处理空字符串
    if not name:
        return []
    # 检查首尾是否包含小数点
    if name.startswith('.') or name.endswith('.'):
        return []
    # 检查是否存在多个连续小数点
    if '..' in name:
        return []
    # 分割字符串并验证格式合法性
    parts = name.split('.')
    if len(parts) != 2 or not parts[0] or not parts[1]:
        return []
    return parts

name = input("Enter name:")
print(filesplitter_to_list(name))

错误场景处理逻辑

  • 空字符串:直接判断输入为空,返回空列表
  • 点位于字符串首尾:通过startswith('.')和endswith('.')检测首尾字符,符合条件则返回空列表
  • 多个连续点:检查字符串中是否包含'..'子串,存在则返回空列表
  • 缺失点:分割后列表长度不等于2(说明无点或多点),或分割后的任意部分为空,返回空列表

测试验证

  • 合法输入myfile.txt → 输出['myfile', 'txt']
  • 输入.myfiletxt. → 输出[]
  • 输入myfile..txt → 输出[]
  • 输入myfiletxt(无点)→ 输出[]
  • 输入空字符串 → 输出[]
  • 输入myfile.(尾点)→ 输出[]
  • 输入.txt(首点)→ 输出[]

内容的提问来源于stack exchange,提问作者Mestari Lion

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:32:11