编程知识 cdmana.com

If the characters in the string are different in length, what method should be used to replace them?

The phenomenon and background of the problem

As the title :
Test whether there are sensitive words in user input , If so, replace the sensitive word with 3 asterisk .

( Suppose sensitive words include : porn violence crazy split )

ensitive=(' porn ',' violence ',' crazy ',' split ')something=input(' Please input anything :')for n in (1,2):    for i in something[::1]:        if i in Sensitive:            something.replace(i,‘***’)print(something)
Operation results and error reporting contents

replace It doesn't work

My solution ideas and tried methods
What I want to achieve



Take the answer :

First , The variables you define n Not used , secondly ,replace The method is to return a new string , Instead of overwriting the original string , So it needs to be reassigned .
Try this change :

Sensitive = (' porn ',' violence ',' crazy ',' split ')something = input(' Please input anything :')for n in (1,2):    for i in range(len(something[:])):        if something[i:n+i] in Sensitive:            something = something.replace(something[i:n+i], '***')print(something)

Running results :

 Please input anything : You're a porn maniac , Don't split up. Hello ******, Don't do it ***

版权声明
本文为[CSDN Q & A]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/134/202205072041112096.html

Scroll to Top