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 )

0

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

6 Comments

You don't even need the list() call. :)
Question is based on the indices so this is not a proper way!
In general for this sort of manipulation, convert to a list, manipulate the indices in the list then join back to a string, but in this specific example as you showed it collapses down beautifully into a join and slice with skip.
@Kasramvd, it's an XY Problem.
@TigerhawkT3 Yeah a sort of! but not completely!
|
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$'

1 Comment

You could shorten this slightly with '$' if i%2 else j.
1
name = "ABCDEFGH"
nameL = list(name)

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

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

Comments

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.

6 Comments

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 +=.
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?
You can't append to an existing string because strings are immutable in Python.
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).
Good to know. Thanks for the post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.