Reputation: 11
I'm trying to change all but the last four characters in a string to the # symbol on output.
Here's what I have currently
>>> v
'0123456789'
>>> for ch in v:
... if ch in v:
... v = v.replace(ch, '#')
...
>>> print v
##########
As you can see, ALL characters are replaced.
I've tried using all types of index slicing methods but nothing seems to work! I've also tried...
>>> v = '0123456789'
>>> for ch in v:
... if ch in v:
... v = v[0:-4].replace(ch, '#') + v[-3:]
...
>>> print v
789
But, as you can see here, it gets rid of all the other characters.
Please help.
Upvotes: 1
Views: 2604
Reputation: 8202
That's not really what replace is for: a sensible usage is:
>>> 'abcbabcba'.replace('ba','zy')
'abczybczy'
What you want is best addressed by string indexing with negative subscripting and string duplication
assert len(v) >= 4
result = ( '#' * (len(v)-4) ) + v[-4:]
Note that assertion. You'll need to code specially for that case if v can ever be shorter than 4 characters.
Upvotes: 1
Reputation: 339
While the solution by @cricket_007 works just fine if you want to replace all characters, if you want to filter some you can use the approach you used. However, the last part in your new v assignment should be v[-4:]
rather than v[-3:]
Upvotes: 0
Reputation: 20417
The .replace()
method is not appropriate for what you're trying to do. It replaces all instances of a character with another:
>>> '123412341234'.replace('1', '#')
'#234#234#234'
So looping through calling replace for each character you find, is pointless.
Instead, just construct a new string from the right number of #
s and the last 4 digits of the original.
'%s%s' % (
'#' * (len(v) - 4),
v[-4:]
)
Upvotes: 0
Reputation: 940
s = "0123456789"
result = "".join(['#' for x in s[:-4]]) + s[-4:]
Upvotes: 4
Reputation: 191728
Python strings are immutable, so something like this should work. No loops
>>> v = '0123456789'
>>> '#'*(len(v) - 4)+v[-4:]
'######6789'
The thing about replace is that what if you had 333333
and you replace('3', '#')
? Everything becomes a #
, right?
Upvotes: 5