3 回答

TA貢獻1856條經驗 獲得超5個贊
您當前的版本失敗,因為字符串在創建后無法修改(請參閱注釋);相反,執行以下操作:
amended_str = normalize_str(orig_str)
您想要的縮短版本是:
def normalize_str(in_str):
return in_str.replace(' ', '').replace('-', '')
# Or
normalize_str = lambda s: s.replace(' ', '').replace('-', '')
注意:您無法修改作為參數傳遞的字符串,因為字符串是不可變的 - 這意味著一旦創建,它們就無法修改。

TA貢獻1854條經驗 獲得超8個贊
字符串是不可變的對象,這意味著在Python中,函數外部的原始字符串不能被修改。因此,您需要顯式返回修改后的字符串。
def normalise_str(old_string):
return old_str.replace(' ','').replace('-', '')
orig_str = "foo - bar"
amended_str = normalise_str(old_string)
print(amended_str) # Should print foobar

TA貢獻1810條經驗 獲得超5個贊
您需要輸入舊字符串,進行更改,然后將最終的臨時字符串返回給變量。
#This is what my function looks like
def normalise_str(old_string): #def func
temp_string = old_string.replace(" ", "") #rm whitespace
temp_string = temp_string.replace("-", "") #rm hyphens
return temp_string #assign newly modified str to var
#This is what I would like to achieve
orig_str = "foo - bar"
s = normalise_str(orig_str)
print(s) #I would like this to return "foobar"
添加回答
舉報