Details:
Remove n exclamation marks in the sentence from left to right. n is positive integer.
remove("Hi!",1) === "Hi"
remove("Hi!",100) === "Hi"
remove("Hi!!!",1) === "Hi!!"
remove("Hi!!!",100) === "Hi"
remove("!Hi",1) === "Hi"
remove("!Hi!",1) === "Hi!"
remove("!Hi!",100) === "Hi"
remove("!!!Hi !!hi!!! !hi",1) === "!!Hi !!hi!!! !hi"
remove("!!!Hi !!hi!!! !hi",3) === "Hi !!hi!!! !hi"
remove("!!!Hi !!hi!!! !hi",5) === "Hi hi!!! !hi"
remove("!!!Hi !!hi!!! !hi",100) === "Hi hi hi"
My Solution:
def remove(s, n):
l = []
for i in s:
if i == "!" and n > 0:
n -= 1
continue
l.append(i)
return ''.join(l)
Best Practice:
def remove(s, n):
return s.replace('!', '', n)
Tips:
1. 替换字符串中指定数量的单个字符用str.replace('target', 'replace', n)。