[英]Python defining Function
我想創建一個從字符串中刪除空格的函數,到目前為止我所做的是:
def stripped(x):
x = x.replace(' ', '')
string = " yes Maybe So"
我想通過這樣做來剝離空間
string.stripped()
但我一直得到這個錯誤AttributeError:'str'對象沒有'stripped'屬性
我做錯了什么我猜它是簡單的我只是在俯視,提前謝謝。
定義函數時,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'
>>>
請注意您的要求是技術上可行的。 然而,這是一個猴子補丁,不應該使用 。 但僅僅是為了完整性:
>>> _str = str
>>>
>>> class str(_str):
def stripped(self):
return self.replace(' ', '')
>>> string = str(" yes Maybe So")
>>> string.stripped()
' yes Maybe So'
>>>
您無法將方法添加到現有類中。 您可以編寫一個接收並返回字符串的函數:
def stripped(x):
return x.replace(' ', '')
通過傳遞你的字符串來調用它:
s = " yes Maybe So"
s = stripped(s)
如果你想要所有的空格,而不僅僅是空格,你可以做''.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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.