"I'm learning Python"の'learning'を'*******'で置き換える。(置き換えたい文字数相当数の*)
def censor(text,word):
x = []
star = "*"*len(word)
for i in text.split():
x.append(i)
for j in x:
if j == word:
x.insert(x.index(word),star)
x.remove(j)
return " ".join(x)
print censor("I'm learning Python", "learning")
別パターン。
def censor(text, word):
x = text.split()
for i in x:
if i == word:
x[x.index(i)]= "*"*len(word)
return " ".join(x)
print censor("I'm learning Python", "learning")
がしかし、上記だと処理時間がかかってしまうので、enumerate()を使う方が良い。
def censor(text,word):
x = []
star = "*"*len(word)
for i in text.split():
x.append(i)
for index,j in enumerate(x):#here
if j == word:
x.insert(index,star)#here
x.remove(j)
return " ".join(x)
print censor("I'm learning Python", "learning")
def censor(text, word):
x = text.split()
for index,i in enumerate(x):#here
if i == word:
x[index]= "*"*len(word)#here
return " ".join(x)
print censor("I'm learning Python", "learning")
@usai さんありがとうございます!