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

Python中使用join拼接字符串时出现重复下划线问题求助

问题分析与解决

你的代码出现远超预期数量下划线的核心原因有两个:

  1. 字符串未加引号:str = potetoBox会被Python识别为变量而非字符串,正确写法应为str = "potetoBox"。
  2. 正序遍历并修改字符串导致索引偏移:循环基于原字符串长度生成索引,但每次插入下划线后字符串变长,原大写字母的位置会向后移动,后续循环会再次访问到这个大写字母,重复插入下划线。

解决方案

方案1:构建新字符串(推荐)

遍历原字符串的每个字符,将需要的内容添加到列表中,最后拼接成新字符串,避免修改原字符串带来的索引问题:

original_str = "potetoBox"
new_str = []
for char in original_str:
    if char.isupper():
        new_str.append('_')
    new_str.append(char)
print(''.join(new_str))  # 输出:poteto_Box

方案2:倒序遍历索引

倒序遍历原字符串的索引,这样插入下划线不会影响尚未处理的索引(前面的索引位置更小,插入操作在当前索引前,不会干扰后续倒序的索引访问):

str = "potetoBox"
# 从最后一个索引倒序遍历到0
for indx in range(len(str)-1, -1, -1):
    if str[indx].isupper():
        str = ''.join((str[:indx], '_', str[indx:]))
print(str)  # 输出:poteto_Box

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:12:23