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

Python实现字符串单词间空格替换为...失败,求解决方案

问题解决:将句子空格替换为“...”的代码修正

你的代码逻辑思路没问题,但print函数的sep参数用法错了——sep是用来分隔同一个print调用里的多个参数的,而你每次循环只传了一个x给print,所以sep='...'根本不会生效,再加上end="",就把所有单词直接连起来了。

给你两种简单的修正方案:

方案一:用字符串join方法(推荐)

这是Python处理这种拼接需求最简洁高效的方式,直接把分割后的单词列表用...连接起来:

a = input("enter your sentence: ")
# 分割后用...连接所有单词
result = '...'.join(a.split())
print(result)

输入this is a test时,会直接输出this...is...a...test。

方案二:修改循环内的打印逻辑

如果一定要用循环实现,可以在每个单词后添加...,但最后一个单词不加:

a = input("enter your sentence: ")
words = a.split()
for i in range(len(words)):
    if i == len(words) - 1:
        print(words[i], end="")
    else:
        print(words[i], end="...")

或者用enumerate让逻辑更直观:

a = input("enter your sentence: ")
words = a.split()
for idx, word in enumerate(words):
    print(word, end="..." if idx != len(words)-1 else "")

另外注意你代码里的输入提示拼写错误,inter应该是enter,已经顺手修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:20:31