Problems with string and lists (searching and replaceing)
Anton Vredegoor
anton at vredegoor.doge.nl
Sat Sep 20 10:15:45 EDT 2003
jblazi <jblazi at hotmail.com> wrote:
>I should like to search certain characters in a string and when they are
>found, I want to replace other characters in other strings that are at
>the same position (for a very simply mastermind game) for my pupils.
>
>This very simple thing does not seem simple at all.
>
>If I use strings, I cannot replace their parts (though I can use
>string.find for the searching). I think it is a bad idea that strings are
>not mutable, but I suspect that this has been discussed here for ages.
>
>I can use sequences instead, but then first I have to 'split' and 'join'.
>Additionally, there is no 'find' for sequences (who knows why not) and so
>I can choose between using 'index' that raises an exception (and we have
>not covered exceptions yet) or I can ask whether the character is in the
>string before using 'index' which is a bit artificial from the point of
>view of my pupils. (It is all right with me.)
>
>Do I oversee something?
Yes, UserString. The documentation is a bit sparse, but reading the
module itself provides additional information. Below is a quick test
script.
HTH,
Anton
from UserString import MutableString
def test():
s = MutableString("helo world")
print s
x = 'helo'
y = 'hello'
i = s.find(x)
s[i:i+len(x)] = y
print s
if __name__=='__main__':
test()
#output:
#helo world
#hello world
More information about the Python-list
mailing list