1

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 )

4 Answers4

12

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

csunday95
  • 1,279
  • 10
  • 18
3

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$'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

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.

Andrew
  • 475
  • 4
  • 15
  • The reason why the other solutions use a list with `join` is to avoid this - you are creating a new string object each time you use `+=`. – cdarke Jul 23 '15 at 20:13
  • I did not know that. I figured it was, in effect, appended to an existing string. What's the detail of the operation? Does it (1) create a new string consisting of the old `nstr` concatenated with the new character, (2) delete the old `nstr` and (3) move the new string to `nstr`? – Andrew Jul 23 '15 at 20:18
  • You can't append to an existing string because strings are immutable in Python. – TigerhawkT3 Jul 23 '15 at 20:20
  • Just about, yes. Python is not the only language like this, PHP and Java are examples that are the same. Perl is the odd one out (in so many ways). – cdarke Jul 23 '15 at 20:22
  • Good to know. Thanks for the post. – Andrew Jul 23 '15 at 20:24
  • The discussion is worthwhile, although often repeated here. It would be good to keep. – cdarke Jul 23 '15 at 20:26
1
name = "ABCDEFGH"
nameL = list(name)

for i in range(len(nameL)):
    if i%2==1:
        nameL[i] = '$'

name = ''.join(nameL)
print(name)