了解string方法strip

2024-05-07 17:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用如下所示的内容初始化变量x之后,我使用一个参数应用了strip。剥离的结果出乎意料。当我试图剥离“ios\u static\u analyzer/”时,“rity/ios\u static\u analyzer/”正在剥离。你知道吗

请帮助我知道为什么会这样。你知道吗

>>> print x
/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/

>>> print x.strip()
/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/

>>> print x.strip('/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer

>>> print x.strip('ios_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/secu

>>> print x.strip('analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_

>>> print x.strip('_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static

>>> print x.strip('static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io

>>> print x.strip('_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io

>>> print x.strip('s_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/security/io

>>> print x.strip('os_static_analyzer/')
Users/msecurity/Desktop/testspace/Hy5_Workspace/secu 

Tags: io内容staticanalyzerusersworkspaceiossecurity
3条回答

引自^{} docs

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:

因此,它从字符串的两侧删除参数中的所有字符。你知道吗

例如

my_str = "abcd"
print my_str.strip("da")  # bc

注意:您可以这样想,当它发现在输入参数字符串中找不到的字符时,它会停止从字符串中删除字符。你知道吗

实际上,要删除特定的字符串,应该使用str.replace

x = "/Users/Desktop/testspace/Hy5_Workspace/security/ios_static_analyzer/"
print x.replace('analyzer/', '')
# /Users/msecurity/Desktop/testspace/Hy5_Workspace/security/ios_static_

但是替换会把火柴弄得到处都是

x = "abcd1abcd2abcd"
print x.replace('abcd', '')  # 12

但是如果您只想删除字符串开头和结尾的单词,可以使用RegEx,如下所示

import re
pattern = re.compile("^{0}|{0}$".format("abcd"))
x = "abcd1abcd2abcd"
print pattern.sub("", x)   # 1abcd2

Python x.strip(s)从字符串x的开头或结尾删除s中出现的任何字符!所以s只是一组字符,而不是与子字符串匹配的字符串。你知道吗

我想,你需要的是replace

>>> x.replace('ios_static_analyzer/','')
'/Users/msecurity/Desktop/testspace/Hy5_Workspace/security/'

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new.

因此,您可以将字符串替换为空,并获得所需的输出。你知道吗

相关问题 更多 >