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

Python使用sep="..."无法替换空格为三个句号的问题求助

问题原因及解决方法

你之前的代码没达到预期效果,核心是误解了print()函数中sep参数的作用:

  • sep仅用于指定print()里多个参数之间的分隔符,根本不会替换字符串内部的空格。
  • 第一段代码里print(playback, sep="...")只有一个参数,sep完全没生效,自然不会改动原字符串的空格。
  • 第二段代码里sep只是把"hello,"和playback这两个参数用...分隔开,playback本身的空格还是原样保留。

正确解法:用字符串的replace()方法

要替换字符串内部的空格,得用Python字符串自带的replace()方法,它能精准替换字符串里指定的子串。

修正后的第一段代码(匹配你的初始需求):

playback = input("Please write something that you'd like to see printed. Spaces will be replaced with 3 periods. ")
# 将原字符串中的空格替换为三个句号
formatted_text = playback.replace(" ", "...")
print(formatted_text)

输入this is cs50p,会输出this...is...cs50p,完全符合你的预期。

修正后的第二段代码:

playback = input("Please write something that you'd like to print out. Spaces will be replaced with 3 periods. ")
formatted_text = playback.replace(" ", "...")
print("hello,", formatted_text, sep="...")

输入this is cs50p,会输出hello,...this...is...cs50p,既实现了参数间的分隔,也替换了原字符串内的空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:51:34