2017-01-22 73 views
0

我想從一個字符串在Python 3下刪除一個角色是我的代碼:試圖從一個字符串在Python刪除一個3字

#Function that removes a character from a string 
def removeChar(character, string): 
    new_string = string.replace(character, "") 

print(removeChar("e", "Hello World")) 

不過,這一方案的輸出只是None。我的代碼有什麼問題?

+2

,因爲你沒有返回'new_string'值... –

+1

加上'在函數的最後返回new_string' – rassar

回答

2

你有自己的功能如下後返回new_string

def removeChar(character, string): 
    new_string = string.replace(character, "") 
    return new_string 

print(removeChar("e", "Hello World")) 
2

那麼如果一個函數沒有return任何東西,Python解釋器會讓它返回None。所以,你應該聲明:

def removeChar(character, string): 
    returnstring.replace(character, "")

而且你真的不從字符串中去掉一個字符,字符串是不變,您所創建的字符串,其中的字符缺失相比定字符串的一個副本。

相關問題