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

如何输出无空格的句子或短语?现有Python代码输出异常如何修复?

问题原因

当前代码将筛选后的非空格字符存在列表中,直接返回列表会导致输出为拆分的单个字符格式,只需将列表拼接为完整字符串再返回即可得到符合要求的结果。

方案1 基于原有逻辑修改

仅修改返回值部分,使用join方法拼接列表元素:

def output_without_whitespace(input_str):
   lst = []
   for char in input_str:
       if char != ' ': 
           lst.append(char)
   return ''.join(lst)

if __name__ == '__main__':
   phrase = input('Enter a sentence or phrase:\n')
   print(output_without_whitespace(phrase))

方案2 更简洁的实现

直接调用字符串内置的replace方法替换所有空格,代码更精简:

def output_without_whitespace(input_str):
   return input_str.replace(' ', '')

if __name__ == '__main__':
   phrase = input('Enter a sentence or phrase:\n')
   print(output_without_whitespace(phrase))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:06:03