in-place string modifications in Python

in-place string modifications in Python

Dont use a string, use something mutable like bytearray:

#!/usr/bin/python

s = bytearray(my dog has fleas)
for n in xrange(len(s)):
    s[n] = chr(s[n]).upper()
print s

Results in:

MY DOG HAS FLEAS

Edit:

Since this is a bytearray, you arent (necessarily) working with characters. Youre working with bytes. So this works too:

s = bytearray(x81x82x83)
for n in xrange(len(s)):
    s[n] = s[n] + 1
print repr(s)

gives:

bytearray(bx82x83x84)

If you want to modify characters in a Unicode string, youd maybe want to work with memoryview, though that doesnt support Unicode directly.

The Python analog of your C:

for(int i = 0; i < strlen(s); i++)
{
   s[i] = F(s[i]);
}

would be:

s = .join(F(c) for c in s)

which is also very expressive. It says exactly what is happening, but in a functional style rather than a procedural style.

in-place string modifications in Python

you can use the UserString module:

 >>> import UserString
... s = UserString.MutableString(Python)
... print s
Python
>>> s[0] = c
>>> print s
cython

Leave a Reply

Your email address will not be published. Required fields are marked *