How to replace characters in a string which we know the exact indexes in python?
Ex : name = "ABCDEFGH" I need to change all odd index positions characters into '$' character.
name = "A$C$E$G$" (Considered indexes bigin from 0 )
Also '$'.join(s[::2]) Just takes even letters, casts them to a list of chars and then interleaves $
''.join(['$' if i in idx else s[i] for i in range(len(s))]) works for any index array idx
list() call. :)You can use enumerate to loop over the string and get the indices in each iteration then based your logic you can keep the proper elements :
>>> ''.join([j if i%2==0 else '$' for i,j in enumerate(name)]) 'A$C$E$G$' '$' if i%2 else j.You can reference string elements by index and form a new string. Something like this should work:
startingstring = 'mylittlestring' nstr = '' for i in range(0,len(startingstring)): if i % 2 == 0: nstr += startingstring[i] else: nstr += '$' Then do with nstr as you like.
join is to avoid this - you are creating a new string object each time you use +=.nstr concatenated with the new character, (2) delete the old nstr and (3) move the new string to nstr?