Python3中使用strip()方法后字符串部分字符莫名消失的原因求解
问题原因及解决方法
核心问题:误解了str.strip()的作用
str.strip()的参数不是要移除的固定子串,而是一个字符集合——它会把字符串首尾所有属于这个集合的字符全部移除,直到碰到不在集合里的字符为止。
看你的代码:
input = "Please convert 899999999999 using AaBbCcDdEeFfGgHhIiJjKkaaaaLlaaa " output = input.strip('Please convert')
你传入的'Please convert'会被拆解成这些字符(去重后):P, l, e, a, s, , c, o, n, v, r, t。
再看字符串末尾的Llaaa :
- 末尾的空格、小写
a、小写l都属于这个字符集合,所以会被逐个移除; - 直到碰到大写
L(不在集合里),才停止移除操作。
这就是为什么最终输出末尾少了laaa。
正确的实现方式
如果你的需求是移除开头的"Please convert "这个固定前缀,有两种靠谱方法:
- 字符串切片(兼容所有Python3版本)
prefix = "Please convert " input_str = "Please convert 899999999999 using AaBbCcDdEeFfGgHhIiJjKkaaaaLlaaa " if input_str.startswith(prefix): output = input_str[len(prefix):] print(output)
str.removeprefix()(Python3.9及以上版本可用)
input_str = "Please convert 899999999999 using AaBbCcDdEeFfGgHhIiJjKkaaaaLlaaa " output = input_str.removeprefix("Please convert ") print(output)
两种方法都能得到正确结果:899999999999 using AaBbCcDdEeFfGgHhIiJjKkaaaaLlaaa
内容的提问来源于stack exchange,提问作者Sean Z
相关产品推荐
相关产品推荐

