Nistor Paul
Nistor Paul

Reputation: 21

read a string position

I'm struggling with a basic problem in python. I need to read a string at a certain position in order to modify it.

Example: for the string 'abcd' I want to read the 3rd position (2nd really because you start from 0) and change it to the next letter of the alphabet, 'abdd'. However, if string happened to be 'abrd' that should change to 'absd', etc. So, I need to read and to write in a specific position and let everything else untouched; should be the simplest thing in the world, but I can't find how to do it.

Upvotes: 2

Views: 3432

Answers (2)

kojiro
kojiro

Reputation: 77099

At its core the answer to your question is simple: use list slice syntax:

>>> string='abcd'
>>> print string[:2] + 'd' + string[3:]
abdd

If you can assume that it's safe to just increment the ordinal value of the string, then you can just do:

>>> string='abrd'
>>> string=string[:2] + chr(ord(string[2]) + 1) + string[3:]

Since it's not specified in your question, I'll assume that's what you need. You may find some rough patches if you wanted to loop from 'z' to 'a', or deal specially with different letter cases or unicode character sets.

If you do have a more sophisticated problem than just incrementing the ord, consider using a translation table

Upvotes: 2

nqngo
nqngo

Reputation: 528

Aside from @kojiro answer. Another way of doing it is switching the string to list and join it back. For example:

S = 'abcd'
// Convert to list
L = list(S)
// Change 3rd position
L[3] = 'd'
// Join it back and print
print ''.join(L)

However, if you need to substitute different characters, you can define a dictionary mapping to ease the conversion process. For example:

// Define {a -> x} mapping.
M = {'c': 'd', 'r': 's'}
// Substitution
L[3] = M[L[3]]

Upvotes: 1

Related Questions