我正在尝试从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
。我的代码出了什么问题?
答案 0 :(得分:2)
如果一个函数没有return
任何东西,那么Python解释器会让它返回None
。所以你应该说:
def removeChar(character, string):
return string.replace(character, "")
此外,你并不是从字符串中删除字符,字符串是不可变,你创建了字符串的副本,其中字符与给定的字符相比丢失了字符串。
答案 1 :(得分:2)
您必须在自己的功能之后返回new_string
,如下所示:
def removeChar(character, string):
new_string = string.replace(character, "")
return new_string
print(removeChar("e", "Hello World"))