Python代码在IDLE外运行时输出字符串插入额外空格的问题排查
终端输出特殊字符时插入额外空格问题
import re def convert_to_lower(match_obj): if match_obj.group() is not None: return match_obj.group().lower() while True: print("Input text") OUTPUT = input() if OUTPUT == "CHANGE MODE": break OUTPUT = re.sub("[A-Z]", convert_to_lower, OUTPUT) OUTPUT = OUTPUT.replace("a","🝓") OUTPUT = OUTPUT.replace("c","🝌") OUTPUT = OUTPUT.replace("e","🝗") OUTPUT = OUTPUT.replace("f","🝡") OUTPUT = OUTPUT.replace("i","🜌") OUTPUT = OUTPUT.replace("o","🜨") OUTPUT = OUTPUT.replace("r","🝈") OUTPUT = OUTPUT.replace("t","🝨") OUTPUT = OUTPUT.replace("u","🝣") OUTPUT = OUTPUT.replace("v","🜉") OUTPUT = OUTPUT.replace("w","🝃") OUTPUT = OUTPUT.replace("x","🝍") OUTPUT = OUTPUT.replace("y","🝘") print(OUTPUT)
这段代码在IDLE shell中运行无异常,但在IDLE之外的终端运行时,只要有字符被替换为特殊符号,输出字符串就会插入额外空格。空格的数量和位置随字符串内容变化,但替换字符位置一致的字符串(如“lalalalala”和“nanananana”)出现的问题完全相同,且空格通常出现在第30个字符之后。推测问题与终端无法正常显示这些特殊字符(显示为带问号的方框)有关,但不确定具体原因。
已尝试的解决手段:
- 更换替换字符:只要字符无法被终端正常显示(仅“⭙”例外),问题就会持续存在
- 使用
re.sub替代OUTPUT.replace进行字符替换,问题仍未解决
问题截图:
内容的提问来源于stack exchange,提问作者Qaos
相关产品推荐
相关产品推荐

