2017-06-22 76 views
1

我想要從一個字符串去掉空格的功能,我至今是:Python的定義功能

def stripped(x): 
    x = x.replace(' ', '') 

string = " yes Maybe So" 

我想這樣做

string.stripped() 

剛剛剝離的空間但我一直得到這個錯誤 AttributeError:'str'對象沒有屬性'剝離'

我在做什麼錯誤我猜這是簡單的東西我只是忽略克,提前感謝。

+0

您需要將字符串賦予「已剝離」。 'stripped'不是一個字符串方法。 – Carcigenicate

+1

你想'剝離'到'返回x'然後'字符串=剝離(字符串)' – castis

+0

[實現自定義字符串方法]的可能重複(https://stackoverflow.com/questions/4519702/implementing-a-custom -string-method) – depperm

回答

1

當你定義你的功能,你的Python創建一個名爲stripped一個孤獨的函數對象。它不會將您的功能添加到內建的str對象。你剛纔

need to call your method on the string normally: 

>>> def stripped(x): 
    x = x.replace(' ', '') 


>>> string = " yes Maybe So" 
>>> stripped(string) 
>>> 

不過請注意string將不會被修改,你需要將它返回x.replace()的結果,並分配給string

>>> def stripped(x): 
    return x.replace(' ', '') 

>>> string = " yes Maybe So" 
>>> string = stripped(string) 
>>> string 
' yes Maybe So' 
>>> 

注意你問什麼是techinally可能。 但是它是一個猴子補丁,不應該使用。但只是爲了完整性:

>>> _str = str 
>>> 
>>> class str(_str): 
    def stripped(self): 
     return self.replace(' ', '') 


>>> string = str(" yes Maybe So") 
>>> string.stripped() 
' yes Maybe So' 
>>> 
+0

嘿嘿,我覺得我不得不退還它,我不理解這一點,謝謝你的幫助。我會盡快接受。 – Cannon

+0

@Cannon很高興我能幫到你。 –

0

您不能將方法添加到類似的現有類中。你可以寫接收並返回一個字符串的函數:

def stripped(x): 
    return x.replace(' ', '') 

,並通過將您的字符串調用它:

s = " yes Maybe So" 
s = stripped(s) 
-1

如果你希望所有的空白,而不僅僅是空間,你可以做''.join(string.split())

def stripped(string): 
    return ''.join(string.split()) 

string = stripped(' yes Maybe So') 

# But it would also handle this 
string = stripped(' yes \n Maybe So\n') 
assert string == 'yesMaybeSo' 
+0

儘管這也許提供了一個更好的方法,但它並沒有回答主要問題,這可能就是爲什麼你被低估了。 (我沒有downvote)。 –

-1

您是通過執行string.stripped()您已經定義的函數調用的字符串的方法將字符串作爲參數,並且不向Python中的字符串對象添加方法。要剝離字符串,以這種方式將字符串傳遞給函數:

>>> s = "hello foo" 
>>> stripped(s) 
>>> s 
"hellofoo" 
+1

這個答案是錯誤的。參數不會被Python中的指針傳遞,所以's'將不會改變。 –

+0

@ChristianDean我什麼時候指出使用指針? –

+0

你沒有,但你似乎認爲傳遞變量到Python中的函數,就像傳遞一個指針。不是這樣。 's'永遠不會被修改。嘗試自己的方法,你會明白我的意思。 –