Python 的 strip()有坑啊!你们谁遇到了?

2018-06-04 09:59:22 +08:00
 kkhu2004

s="s,fadsafdsafasf"

print(s.strip("s,"))

输出结果是预计的 fadsafdsafasf

但是!但是!

print(s.strip("s,f"))

输出结果居然是 adsafdsafa

4467 次点击
所在节点    问与答
21 条回复
easylee
2018-06-04 10:08:27 +08:00
给你个例子,你参考一下:

![]( https://i.loli.net/2018/06/04/5b149edc12bd3.png)

图截取自“菜鸟教程"。
ThirdFlame
2018-06-04 10:09:39 +08:00
>>> print(s.strip("s,"))
fadsafdsafasf
>>> print(s.strip("s,f"))
adsafdsafa
>>> print(s.strip("fs,"))
adsafdsafa
>>>

显然是 1 个字符 1 个字符处理的
aheadlead
2018-06-04 10:11:33 +08:00
RTFM
virusdefender
2018-06-04 10:11:39 +08:00
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>>
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
loryyang
2018-06-04 10:11:54 +08:00
去读下 API,这是你有坑,兄弟
不要经常以为你有了大发现,人人都在用的东西,哪有那么容易错,先自我检查,是不是自己蠢了
aheadlead
2018-06-04 10:12:16 +08:00
polaa
2018-06-04 10:12:16 +08:00
。。。 我觉得没问题,strip return 不就是这么 return 的么
eurokingbai2
2018-06-04 10:13:25 +08:00
没明白楼主想要什么字符串,python 这输出不对么?
shuax
2018-06-04 10:21:51 +08:00
RTFM
liuxey
2018-06-04 10:24:41 +08:00
语言内置的基础 API 要是有问题那相关的帖子和新闻早就爆出来了

我举个不恰当的例子:如果你访问不了百度,你觉得是百度挂了还是你网络连接有问题
Troevil
2018-06-04 10:29:14 +08:00
strip 和 trim 还是有区别的
dassh
2018-06-04 10:32:36 +08:00
>>> 'abcde'.strip('ba')
'cde'
kkhu2004
2018-06-04 10:53:14 +08:00
@ThirdFlame
@virusdefender
手动再次感谢,:)
kkhu2004
2018-06-04 11:06:37 +08:00
@aheadlead
@loryyang
@polaa
@shuax
@Troevil

多谢,初学,只是练习题。是我理解有误。用 strip 直接过滤字符串不合适。
aheadlead
2018-06-04 11:10:04 +08:00
@kkhu2004 #14 用 s.replace("s,f", "")
recall704
2018-06-04 13:23:59 +08:00
@aheadlead 那如果我只想去掉首尾呢?
aheadlead
2018-06-04 13:29:36 +08:00
@recall704 #16
$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '12345'
>>> s = s[1:-1]
>>> print(s)
234
>>>
kkhu2004
2018-06-04 13:30:11 +08:00
@recall704 暂时不知道,目前刚刚学,只练习到了这地步。
楼上( 15 楼)的方法是替换所有的相关字符串,不适用。
mulog
2018-06-05 05:25:31 +08:00
>>> s="s,fadsafdsafasf"
>>> target = 's,f'
>>> print(s[len(target) if s.startswith(target) else 0: len(s) - len(target) if s.endswith(target) else len(s)])
adsafdsafasf
thinker3
2018-06-05 09:40:37 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/460131

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX