LoginSignup
1
1

More than 5 years have passed since last update.

'ある文字'を'指定した文字'で置き換える

Last updated at Posted at 2015-10-28

"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 さんありがとうございます!

1
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1