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 to use a list of numbers as index inputs

So I have a list of numbers (answer_index) which correlate to the index locations (indicies) of a characters (char) in a word (word). I would like to use the numbers in the list as index inputs later (indexes) on in code to replace every character except my chosen character(char) with "*" so that the final print (new_word) in this instance would be (****ee) instead of (coffee). it is important that (word) maintains it’s original value while (new_word) becomes the modified version. Does anyone have a solution for turning a list into valid index inputs? I will also except easier ways to meet my goal. (Note: I am extremely new to python so I’m sure my code looks horrendous) Code below:

word = 'coffee' 
print(word)
def find(string, char):
  for i, c in enumerate(string):
        if c == char:
            yield i

string = word
char = "e"
indices = (list(find(string, char)))
answer_index = (list(indices))
print(answer_index)
for t in range(0, len(answer_index)):
 answer_index[t] = int(answer_index[t])
indexes = [(answer_index)] 
new_character = '*' 
result = '' 
for i in indexes:
    new_word = word[:i] + new_character + word[i+1:] 
print(new_word)

>Solution :

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

The easiest and fastest way to replace all characters except some is to use regular expression substitution. In this case, it would look something like:

import re
re.sub('[^e]', '*', 'coffee')  # returns '****ee'

Here, [^...] is a pattern for negative character match. '[^e]' will match (and then replace) anything except "e".

Other options include decomposing the string into an iterable of characters (@PaulM’s answer) or working with bytearray instead

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