如何输出无空格的句子或短语?现有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
相关产品推荐
相关产品推荐

