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

Python基础程序问题:字符串字符间插入'-'时末尾多符号如何解决

问题原因

你当前的代码逻辑是遍历字符串的每一个字符时,都固定在字符末尾追加'-'作为输出结束符,因此最后一个字符输出后也会多出不需要的分隔符。

解决方案

方案1:优先使用Python内置的str.join()方法(最简洁高效)

join()是Python专门用于拼接可迭代对象元素的方法,会自动在两个相邻元素之间插入指定分隔符,不会在首尾额外添加内容,完全适配你的需求:

string = input("Enter the string to be traversed: ")
print('-'.join(string))

输入helloworld时,输出结果为h-e-l-l-o-w-o-r-l-d,符合预期。

方案2:循环实现的修改方式

如果你需要保留循环写法,只需要增加最后一个字符的判断即可:

string = input("Enter the string to be traversed: ")
length = len(string)
for index, char in enumerate(string):
    # 最后一个字符直接输出,不需要追加'-'
    if index == length - 1:
        print(char)
    else:
        print(char, end='-')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:54:03