Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i replace character in a string?

hi i’m trying to simulate what the user might type for one word i.e hello so basically I have it printed out to the terminal _ _ _ _ _ and I want to replace the "_" with lets say "l" and match where it is in the string,here is my code

import re
str1="hello"
lettercheck="l"
a=re.search(lettercheck,str1)
span=(a.span())
print(span)
print(str1[span[0])
count=0
ab="_"
for char in str1:
    print(ab,end=" ")
    if lettercheck==char
    count +=1
    replacechar=str1.replace(ab,str1[span[0]])
    print(replacechar)

which prints out
_ _ _ hello
_ hello
_
can anyone explain where I went wrong here and what can I do to fix it? note the count is just for how times how to time the letter recurrences which i will work on later on my code this is just an example to try to understand what is going on

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

All of the searching and replacing can be simplified. The regex library is not needed here:

str1 = 'hello'
lettercheck = "l"

positions = [pos for pos, char in enumerate(str1) if char == lettercheck]

for i in range(len(str1)):
    if i in positions:
        print(lettercheck, end='')
    else:
        print('_', end='')

returns:

__ll_
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading