Replace values in a string

2024/10/13 2:16:35

So the challenge was to replace a specific word in a sentence with asterisks with equivalent length to that word - 3 letters --> 3 asterisks etc.

Section One does not work, but Section Two does - can anyone critique Section One and maybe point out the possible mistake I was making, as the logic seemed sound originally?

def censor(text, word):for c in text:if c == word:                         ## this line was totally wrongtext.replace(c, "*" * len(c))return text

The next segment does work, then CodeAcademy's answer was way different:

def censor(text, word):a = "*" * len(word)for c in text:nw = text.split(word)return a.join(nw)

How would you approach this task?

Answer

The second solution is not perfect either:

def censor(text, word):a = "*" * len(word)nw = text.split(word)  # no need for a loop here, one split catches all occurrencesreturn a.join(nw)

For your first attempt:

def censor(text, word):# for c in text:  # loops char by char#  if c == word:  # one character likely won't be your word#    text.replace(c, "*" * len(c))  # does nothing, string is immutablereturn text.replace(word, "*" * len(word))  # simple!
https://en.xdnf.cn/q/118131.html

Related Q&A

Select n data points from plot

I want to select points by clicking om them in a plot and store the point in an array. I want to stop selecting points after n selections, by for example pressing a key. How can I do this? This is wha…

Python azure uploaded file content type changed to application/octet-stream

I am using python Azure sdk. When the file uploaded its content type changed to application/octet-stream. I want to set its default content type like image/png for PNG image.I am using following method…

the dumps method of itsdangerous throws a TypeError

I am following the guide of 『Flask Web Development』. I want to use itsdangerous to generate a token, but some problems occured. Here is my code:def generate_confirmation_token(self, expiration=3600):…

SP 500 List python script crashes

So I have been following a youtube tutorial on Python finance and since Yahoo has now closed its doors to the financial market, it has caused a few dwelling problems. I run this codeimport bs4 as bs im…

sleekxmpp threaded authentication

so... I have a simple chat client like so:class ChatClient(sleekxmpp.ClientXMPP):def __init__(self, jid, password, server):sleekxmpp.ClientXMPP.__init__(self, jid, password, ssl=True)self.add_event_han…

DoxyPy - Member (variable) of namespace is not documented

I get the error message warning: Member constant1 (variable) of namespace <file_name> is not documented. for my doxygen (doxypy) documentation. I have documented the file and all functions and cl…

to_csv append mode is not appending to next new line

I have a csv called test.csv that looks like:accuracy threshold trainingLabels abc 0.506 15000 eew 18.12 15000And then a dataframe called summaryDF that looks like:accu…

Optional keys in string formats using % operator?

Is is possible to have optional keys in string formats using % operator? I’m using the logging API with Python 2.7, so I cant use Advanced String Formatting.My problem is as follow:>>> impor…

HDF5 headers missing in installation of netCDF4 module for Python

I have attempted to install the netCDF4 module several times now and I keep getting the same error:Traceback (most recent call last):File "<string>", line 17, in <module>File &quo…

How to catch network failures while invoking get() method through Selenium and Python?

I am using Chrome with selenium and the test run well, until suddenly internet/proxy connection is down, then browser.get(url) get me this:If I reload the page 99% it will load fine, what is the proper…