2014-02-19 33 views
2

用下面顯示的內容初始化一個變量x後,我應用帶有參數的strip。帶鋼的結果是意想不到的。正如我試圖剝離「ios_static_analyzer /」,「rity/ios_static_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 

回答

1

你需要什麼,我想,是replace

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

字符串。替代(S,舊,新[,maxreplace])

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

所以,你可以用什麼代替你的字符串,並得到所需的輸出。

0

的Python x.strip(s)從begginning或字符串x出現在s任何字符的最後刪除!所以s只是一組字符,而不是爲子字符串匹配的字符串。

4

str.strip docs

返回去除了開頭和結尾字符 字符串的副本引用。字符參數是一個字符串,用於指定要刪除的字符組。如果省略或無,字符參數 默認爲刪除空白。 chars參數不是前綴或 後綴;相反,其值的所有組合都被剝離:

因此,它會從字符串的兩邊刪除參數中的所有字符。

例如,

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 
+0

感謝您的快速回復。這很有幫助。我會養成閱讀官方文件的習慣。可能這會有所幫助。不管怎樣,再次感謝。 – Deepak

0

string.strip刪除一組作爲參數給出的字符。 chars參數不是前綴或後綴;相反,其值的所有組合都被剝離。

0

strip不會從對象中刪除作爲參數給出的字符串;它在參數中刪除了字符。 在這種情況下,strip將字符串s_static_analyzer/視爲需要刪除的字符的迭代。