遍历string向新串添加符合条件字符时输出空串问题咨询
字符串筛选返回空串问题修复
你遇到的空输出问题绝大多数都是由字符串拼接时没有重新赋值导致的,Python中字符串是不可变对象,str + char 运算会生成新的字符串,不会修改原来的字符串变量,这是最常见的出错原因。
常见错误写法
old_str = "test1234" new_str = "" # 例:过滤所有数字 for char in old_str: if not char.isdigit(): # 错误:仅执行拼接运算,没有将结果赋值给new_str new_str + char print(new_str) # 输出为空
修复方法
将拼接结果重新赋值给新字符串变量即可:
old_str = "test1234" new_str = "" for char in old_str: if not char.isdigit(): # 两种写法都可以,后者是简写 # new_str = new_str + char new_str += char print(new_str) # 输出 test
其他可能的排查点
- 筛选条件逻辑写反,导致没有字符能满足添加要求
- 循环缩进错误,添加字符的逻辑没有被包含在for循环体内
- 遍历的源字符串变量引用错误,实际遍历了空值
内容的提问来源于stack exchange,提问作者Goetz.3
相关产品推荐
相关产品推荐

