Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

python - Using .replace function

I have a code with more than 2500 lines that contains several references to GIS layers. I need to replace these layers in the code for several web maps so I have to find a way to automate a find and replace function.

Following a video example, I went on and created my own version of but couldn't get it to work. So, after failing at troubleshooting and googleing I decided to replicate exactly what I see in the video and oh surprise! it turns out it doesn't for me either.

curseWords = ["crap", "butt", "fork"]
niceWords = ["poo", "buttox", "spoon"]
dirtySentence = "You crap, butt in fork"

def Censor(curseWords, niceWords, dirtySentence):
    for i in range(len(niceWords)):
        dirtySentence = dirtySentence.replace(curseWords[i], niceWords[i])

    return dirtySentence

print(dirtySentence)

I expected this code would change dirtySentence to You poo, buttox in spoon but it doesn't do it. Anyone has any idea what might be wrong with this piece of code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You forget to call your defined function Censor. See below:

curseWords = ["crap", "butt", "fork"]
niceWords = ["poo", "buttox", "spoon"]
dirtySentence = "You crap, butt in fork"

def Censor(curseWords, niceWords, dirtySentence):
    for i in range(len(niceWords)):
        dirtySentence = dirtySentence.replace(curseWords[i], niceWords[i])

    return dirtySentence


dirtySentence = Censor(curseWords, niceWords, dirtySentence) # call the defined function
print(dirtySentence)

Output: You poo, buttox in spoon


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...