Reputation: 5
I'm trying to creating a code that prints till 'n' and replaces the rest of the characters with "*". This is my code so far"
def replace(s,n):
return s.replace(s[n:], "*")
However it outputs
replace("hello", 2)
'he*'
it should be 'he***'
Upvotes: 0
Views: 97
Reputation: 19634
You should multiply "*"
by the number of characters you want to replace. In addition, you should add (len(s)-n)*"*"
after s[n:]
instead of replacing (as the same set of characters may appear in several places in the string). You may do that as follows:
def replace(s,n):
return s[:n]+(len(s)-n)*"*"
replace('hello', 2)
This prints 'he***'
Upvotes: 2
Reputation: 95948
There are two fundamental issues. First, s.replace
will replace the entire first argument with the second. And perhaps even more important, it replaces it anywhere it finds it on the string. So, consider the following example:
>>> def replace(s,n):
... return s.replace(s[n:], "*")
...
>>> replace('lalahahalala', 8)
'*haha*'
>>>
Instead, you should take a different approach, iterate the string, returning the character in that string if the index is < n
, else, return '*'
:
>>> def replace(s, n):
... return ''.join(c if i < n else '*' for i,c in enumerate(s))
...
>>> replace("hello", 2)
'he***'
>>> replace('lalahahalala', 8)
'lalahaha****'
Here is a version of the above using a for-loop instead of a generator expression:
>>> def replace(s, n):
... char_list = []
... for i, c in enumerate(s):
... if i < n:
... char_list.append(c)
... else:
... char_list.append('*')
... return ''.join(char_list)
...
>>> replace('hello', 2)
'he***'
>>> replace('lalahahalala', 8)
'lalahaha****'
>>>
Upvotes: 1
Reputation: 3735
You can slice s
until n
position and then concatenate the rest of the string using *
operator. You don't need to use replace
method:
def replace(s,n):
return s[:n] + (len(s)-n)*'*'
The output is:
replace('hello', 2)
'he***'
Upvotes: 0
Reputation: 126787
The replace
approach is fundamentally flawed, because replace
looks for a substring to replace anywhere in the source string, it's not for replacing characters at some position. Even with the "fixed" version by @MiriamFarber (now he edited it, look at the revision history) you'd get erroneous output like
replace("chachacha", 6) # returns *********
What you want is to truncate the string at the requested position, and append to it a string of as many asterisks as the characters you removed.
def replace(s, n):
return s[:n] + '*'*(len(s)-n)
Upvotes: 0