Reputation: 43
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 )
Upvotes: 1
Views: 893
Reputation: 113
name = "ABCDEFGH"
nameL = list(name)
for i in range(len(nameL)):
if i%2==1:
nameL[i] = '$'
name = ''.join(nameL)
print(name)
Upvotes: 1
Reputation: 1319
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
Upvotes: 12
Reputation: 513
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.
Upvotes: 1
Reputation: 107287
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$'
Upvotes: 3