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 )
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
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$'
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.
name = "ABCDEFGH"
nameL = list(name)
for i in range(len(nameL)):
if i%2==1:
nameL[i] = '$'
name = ''.join(nameL)
print(name)