Reputation: 1
Replacing of a particular character with '#' but replacing is not happening.What is wrong in the code?
Input:
A="234"
for i in range (len(A)):
if (A[i].isdigit()):
print(A[i])
A.replace(A[i],"#");
print(A)
output:
2
3
4
234
Upvotes: 0
Views: 730
Reputation: 41872
For the code you ask about, the suggestion provided by @AnnZen (+1) is sound, though I would toss the semicolon and the extra parentheses. I'd also loop over the characters in the string rather than their indexes:
for c in A:
if c.isdigit():
A = A.replace(c, "#")
As far as solving the complete problem (i.e. adding elimination of non-digits), we don't actually need replace()
:
def convert(string):
result = ''
for character in string:
if character.isdigit():
result += "#"
return result
However, if we want to use replace()
, this seems like an opportunity to also use a defaultdict
:
from collections import defaultdict
dictionary = defaultdict(str, {digit: '#' for digit in "0123456789"})
def convert(string):
for character in string:
string = string.replace(character, dictionary[character])
return string
We can tack on some test code to check it out:
if __name__ == "__main__": # test code
from random import choice, randint
from string import ascii_letters, digits
for tests in range(10):
test_string = ''.join(choice(ascii_letters + digits) for _ in range(randint(10, 20)))
print(repr(test_string), end=' -> ')
test_string = convert(test_string)
print(repr(test_string))
OUTPUT
> python3 test.py
'RzfMD5w3LQO' -> '##'
'NrFsFDDyOit593' -> '###'
'TpURdM0PqTQtaPe3IeP' -> '##'
'TN10mz39BukFNsgf' -> '###'
'ghYfxDLrPSEG5GCO' -> '#'
'9QAJ1PVyegMD' -> '#'
'GOIgOmzpC1ysn4' -> '#'
'LEdR2BafYi9paALgrN' -> '##'
'L2hzkSQNkH2Gb' -> '##'
'E6rnoGi2AamWW01R19' -> '####'
>
The regex idea of @duckboycool has merit, even if the currently suggested implementation doesn't. We don't need two pattern matches, just one to eliminate non-digits:
import re
def convert(string):
return '#' * len(re.sub(r'\D', '', string))
Any of my various convert()
funtions should work with my test code above.
Upvotes: 0
Reputation: 2455
It'd probably be easier to use a regex with python's builtin re
module. Then you could do this in two regexes.
re.sub(r'[^\d]', '', A)
re.sub(r'\d', '#', A)
Upvotes: 0
Reputation: 27577
A.replace(A[i],"#")
will only return another string, it will not override the original. Do this to override it:
A="234"
for i in range (len(A)):
if (A[i].isdigit()):
print(A[i])
A = A.replace(A[i],"#");
print(A)
Upvotes: 1