473,322 Members | 1,473 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Why are strings immutable?

I kind of hate to have to convert a string into a list, manipulate it, and
then convert it back into a string. Why not make strings mutable?
Jul 18 '05 #1
12 2281
On Sat, 21 Aug 2004 03:26:00 GMT,
Brent W. Hughes <br**********@comcast.net> wrote:
I kind of hate to have to convert a string into a list, manipulate it, and
then convert it back into a string. Why not make strings mutable?


Not being able to use strings as dictionary keys would kind of suck :)

--
Sam Holden
Jul 18 '05 #2
Brent W. Hughes wrote:
I kind of hate to have to convert a string into a list, manipulate it, and
then convert it back into a string. Why not make strings mutable?


It is unlikely you are doing whatever it is you need to do
in the best way possible if you are converting to a list and
back. What's the use case here? Can you describe what you
need to accomplish without reference to how you think it should
be accomplished? Maybe there's a better way...

-Peter
Jul 18 '05 #3
Hi Brent,

It is usually best to create a function in which you can
1) pass the string to
2) change it as needed
3) return the modified sting back to the original caller.

Can you tell us a little more about what you are trying to accomplish?

Byron
---
Brent W. Hughes wrote:
I kind of hate to have to convert a string into a list, manipulate it, and
then convert it back into a string. Why not make strings mutable?

Jul 18 '05 #4

"Brent W. Hughes" <br**********@comcast.net> wrote in message
news:chzVc.288437$a24.71659@attbi_s03...
I kind of hate to have to convert a string into a list, manipulate it, and
then convert it back into a string. Why not make strings mutable?
Strings are immutable because they are "value objects".
Consult any good, recent OO design text for what a
value object is, and why it should be immutable.

That said, it would be useful to have a
string buffer object that could be changed.

John Roth

Jul 18 '05 #5
On Sat, 21 Aug 2004 11:34:54 -0400, rumours say that "John Roth"
<ne********@jhrothjr.com> might have written:

[<snip> strings are immutable because...]
That said, it would be useful to have a
string buffer object that could be changed.


array.array('c') is a close substitute.
--
TZOTZIOY, I speak England very best,
"Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek
Jul 18 '05 #6
John Roth wrote:
That said, it would be useful to have a
string buffer object that could be changed.


What about StringIO?
Jul 18 '05 #7
Let me give two examples of where I think it would be nice to be able to
change strings in place:
First example:

I want to add about 20,000 words to the end of a string, something like
this:

Str = [ ]
for i in range(20000):
Word = DoSomeProcessing()
Str += Word

I'd actually like to say Str.extend(Word). As it is, I'm thinking of
something like this:

List = [ ]
for i in range(20000):
Word = DoSomeProcessing()
List.extend(list(Word))
Str = ''.join(List)
Second example:

I would like to reverse a string containing about 120,000 characters. I'd
like to do it in place, but I'm planning to do something like this:

List = list(Str)
List.reverse()
Str = ''.join(List)
Jul 18 '05 #8
Brent W. Hughes wrote:
Let me give two examples of where I think it would be nice to be able to
change strings in place:
Sure, it would be nice sometimes.
But immutable strings provide many nice advantages too.
I want to add about 20,000 words to the end of a string, something like
this:

Str = [ ]
for i in range(20000):
Word = DoSomeProcessing()
Str += Word

I'd actually like to say Str.extend(Word).
If you are doing a lot of that with the string, does it need to be a
single string? I've just speeded up a program significantly by changing
string_var = ...
string_var += ...
string_var += ...
...
to
array_var = ['string']
array_var.append(...)
array_var.append(...)
...
result = "".join(array_var)
(Well, because of how the data was structured I actually used a dict
which was unpacked to a list comprehension which was joined to a string,
but it still speeded things up.)

You might also speed things up with
append_string = array_var.append
append_string(...)
if it is too slow, since that saves a lot of attribute lookups. But
don't make your code more unreadable like that unless it _is_ too slow.
I would like to reverse a string containing about 120,000 characters. I'd
like to do it in place, but I'm planning to do something like this:

List = list(Str)
List.reverse()
Str = ''.join(List)


import array
a = array.array('c', Str)
a.reverse()
Str = a.tostring()

Still needs two new objects, but at least that's a lot fewer than your
list.

--
Hallvard
Jul 18 '05 #9
Think about it. Since strings occupy a fixed
number of bytes in memory, a mutable string would
just be a linked list of strings. For performance
reasons you can't require that everything in memory
gets moved around when you want to add one byte to
a string. Multiply that by 20K and performance
would be terrible. Since a mutable string is just
a list of strings, Python just asks the programmer
to treat it exactly like what it REALLY is. If
you want to append lots of things to a string, build
a list and then join it into a string at the end
of processing.

Your example:

List = [ ]
for i in range(20000):
Word = DoSomeProcessing()
List.extend(list(Word))
Str = ''.join(List)
will work as:

words=[]
for i in xrange(20000):
word = DoSomeProcessing()
words.append(word)

word_string = ' '.join(words)

Notes:

1) You build the word_list by appending words that
come back frmo DoSomeProcessing().

2) If you want a space between your words you must
specify it as the character before .join() call.

3) range(20000) will create a list of length=20000
and interate over it, xrange(20000) will just create
an iterable object that returns the next number on
each sucessive call (saving both memory and the time
to create the 20K list).

4) You should stay FAR away from variables named
list or str (even though you capitalized the first
character). list and str are python functions that
can easily get redefined by accident. List and Str
will work, but I've seen MANY Python programmers walk
on list, str, dict by accident and later wonder why.

HTH,
Larry Bates
Syscon, Inc.

"Brent W. Hughes" <br**********@comcast.net> wrote in message
news:O%rWc.171256$8_6.61890@attbi_s04...
Let me give two examples of where I think it would be nice to be able to
change strings in place:
First example:

I want to add about 20,000 words to the end of a string, something like
this:

Str = [ ]
for i in range(20000):
Word = DoSomeProcessing()
Str += Word

I'd actually like to say Str.extend(Word). As it is, I'm thinking of
something like this:

List = [ ]
for i in range(20000):
Word = DoSomeProcessing()
List.extend(list(Word))
Str = ''.join(List)
Second example:

I would like to reverse a string containing about 120,000 characters. I'd
like to do it in place, but I'm planning to do something like this:

List = list(Str)
List.reverse()
Str = ''.join(List)

Jul 18 '05 #10
"Larry Bates" <lb****@swamisoft.com> writes:
Think about it. Since strings occupy a fixed
number of bytes in memory, a mutable string would
just be a linked list of strings.


Eh? It would be treated just like Python currently treats lists.

In fact, array('B') does just about exactly what Brent is asking for.
Jul 18 '05 #11
Larry Bates wrote:
Your example:

List = [ ]
for i in range(20000):
Word = DoSomeProcessing()
List.extend(list(Word))
Str = ''.join(List)
will work as:

words=[]
for i in xrange(20000):
word = DoSomeProcessing()
words.append(word)

word_string = ' '.join(words)


Or even (using a list comp):

words = ' '.join( [DoSomeProcessing() for i in xrange(20000)] )

Though I have to wonder what you're doing with a 20,000 word string,
built programmatically word-by-word. While I don't know what you're
doing, here, the way you're building it seems to suggest to me that a
list or dictionary may actually be a more natural way to handle your data.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #12
On Mon, 23 Aug 2004 22:11:36 +0200, Hallvard B Furuseth wrote:
If you are doing a lot of that with the string, does it need to be a
single string? I've just speeded up a program significantly by changing
string_var = ...
string_var += ...
string_var += ...
...
to
array_var = ['string']
array_var.append(...)
array_var.append(...)
...
result = "".join(array_var)
(Well, because of how the data was structured I actually used a dict which
was unpacked to a list comprehension which was joined to a string, but it
still speeded things up.)


For PyDS, I contributed a class that does that and offers a += interface,
so it is easy to drop in without too much conversion work. It is very
simple.

In general, you should not use this and you should do it "right" the first
time, but for existing code this can be a convenient make-do.

Replace your initial "myString = ''" with "myString = StringCollector()",
and depending on how you use this you may not need to change the final
use. Otherwise, call "str()" on your StringCollector.

(Note the encoding in iadd; I just added the locale call without testing
it, and you may want to switch it; PyDS actually uses its own system.)

-----------------------------

import locale
class StringCollector:

def __init__(self, string='', encoding = None):
self.buffer = StringIO()
if string: self += string
if encoding in None:
self.encoding = locale.getpreferredencoding()
else:
self.encoding = encoding

def __iadd__(self, other):
if type(string) == types.UnicodeType:
self.buffer.write(other.encode(self.encoding))
else:
self.buffer.write(other)
return self

def __repr__(self):
return '<StringCollector>'

def __str__(self):
return self.buffer.getvalue()

Jul 18 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Rob Jones | last post by:
Hi all, Anyone know the details about String immutability ? I understand the need to have imutable strings at compile time. However if at runtime I have say 8000 strings and then I make a new...
17
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently...
9
by: Klaus Neuner | last post by:
Hello, I would like to understand the reason for the following difference between dealing with lists and dealing with strings: What is this difference good for? How it is accounted for in Python...
4
by: Jens Lippmann | last post by:
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,...
20
by: Trevor | last post by:
I have a couple of questions regarding C# strings. 1) Sometimes I see a string in someone else's code like: string foo = @"bar"; What does the '@' do for you? 2) Is there a performance...
10
by: Eranga | last post by:
I have the following code; string test1 = words;//"Exclud" string test2 ="Exclud"; string test3 = String.Copy(words);//"Exclud" bool booTest1 = test1.Equals(test2);//false bool booTest2 =...
12
by: Water Cooler v2 | last post by:
Are JavaScript strings mutable? How're they implemented - 1. char arrays 2. linked lists of char arrays 3. another data structure I see that the + operator is overloaded for the string class...
16
by: InDepth | last post by:
Now that .NET is at it's fourth release (3.5 is coming soon), my very humble question to the gurus is: "What have we won with the decision to have string objects immutable? Or did we won?" ...
11
by: =?Utf-8?B?TmF2YW5lZXRoLksuTg==?= | last post by:
Hi, 1 - If I write a code like string str = "Hello", how it is getting stored in the memory ? Will it create an array and put the "H" in 0th location, and so on. ? 2 - Is there any way to...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.