Slice assignment for strings?

J

Jens Lippmann

Hi all!

I'm new to Python and just tried to assign values to a portion
of a string, but I don't get it.
My code is:
bits = '\3ff' * bmi.bmiHeader.biSizeImage
ofs = 0x1E2C0
for i in range(0, height):
bits[i*linesize:(i+1)*linesize] = self.shbits[ofs:eek:fs+width/2]

which leads to
...
TypeError: object doesn't support slice assignment

'bits' is a binary string resp. an array of byte so to say.
Note also that the right slice is shorter than the left one.

So, my questions are:
- How do I get it right?
- If slicing seems to be the favorite way to address substrings, why
is it impossible to use it on a left side of an assignment?

kind regards
Jens Lippmann
 
J

John Roth

Jens Lippmann said:
Hi all!

I'm new to Python and just tried to assign values to a portion
of a string, but I don't get it.
My code is:
bits = '\3ff' * bmi.bmiHeader.biSizeImage
ofs = 0x1E2C0
for i in range(0, height):
bits[i*linesize:(i+1)*linesize] = self.shbits[ofs:eek:fs+width/2]

which leads to
...
TypeError: object doesn't support slice assignment

'bits' is a binary string resp. an array of byte so to say.
Note also that the right slice is shorter than the left one.

So, my questions are:
- How do I get it right?
- If slicing seems to be the favorite way to address substrings, why
is it impossible to use it on a left side of an assignment?

Strings are immutable objects, so you can't change them in
any way.

John Roth
 
N

Nicolas Fleury

Jens said:
So, my questions are:
- How do I get it right?
- If slicing seems to be the favorite way to address substrings, why
is it impossible to use it on a left side of an assignment?

Strings are immutable in python; it means you cannot change them
in-place. You can still change the value of variables and do things like:
a = "hello"
a = "a" + a[2:] # producing allo

Strings are immutable, but there's (mutable) containers that might do a
better job for what you want to do. Module array could be a possible
solution (and I'm sure there's others).

Regards,
Nicolas
 
P

Paul Rubin

Jens Lippmann said:
So, my questions are:
- How do I get it right?
- If slicing seems to be the favorite way to address substrings, why
is it impossible to use it on a left side of an assignment?

You can use the array module for what you're doing. See the docs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top