我想定义一个函数,该函数接受一个字符串和该字符串中的一个字母,并输出一个新字符串,该字母出现一次。例如
my_function("happy kitten","p")
'hapy kitten'
或者
my_function("happykitten","t")
'happykiten'
我试过了
def my_function(string, lett):
newString = ""
for char in string: #all characters
for s in string: #character I'm testing
if s == len(s) > 1:
newString+=lett # if there are multiple occurrences of s, replace with lett since its a single char anyway
else:
newString+=char #if not a duplicate, add next char to newString
return newString #("happy kitten","p") returns 'ppppppppppp'
和
def my_function(string, lett):
newString = ""
for char in string: #all characters
for s in string: #character I'm testing
if s == s+1:
newString+=lett # if there are multiple occurrences of s, replace with lett since its a single char anyway
else:
newString+=char #if not a duplicate, add next char to newString
return newString #TypeError: cannot concatenate 'str' and 'int' objects
我的功能出了什么问题?请不要导入或内置函数。