473,708 Members | 2,371 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2317
On Sat, 21 Aug 2004 03:26:00 GMT,
Brent W. Hughes <br**********@c omcast.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**********@c omcast.net> wrote in message
news:chzVc.2884 37$a24.71659@at tbi_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********@jhr othjr.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 = DoSomeProcessin g()
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 = DoSomeProcessin g()
List.extend(lis t(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 = DoSomeProcessin g()
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.appen d(...)
array_var.appen d(...)
...
result = "".join(array_v ar)
(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.appen d
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 = DoSomeProcessin g()
List.extend(lis t(Word))
Str = ''.join(List)
will work as:

words=[]
for i in xrange(20000):
word = DoSomeProcessin g()
words.append(wo rd)

word_string = ' '.join(words)

Notes:

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

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**********@c omcast.net> wrote in message
news:O%rWc.1712 56$8_6.61890@at tbi_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 = DoSomeProcessin g()
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 = DoSomeProcessin g()
List.extend(lis t(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

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

Similar topics

4
3255
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 string from an existing string using substring does that mean that my exisint 8000 strings will be searched incase I am making a duplicate ? That seems quite an overhead ?
17
7396
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 interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix...
9
1658
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 slang? Klaus >>> string1 = "bla" >>> string2 = string1
4
2637
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, height): bits = self.shbits
20
2389
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 loss if I start concatenating strings together
10
5273
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 = test2.Equals("Exclud");//true bool booTest3 = test1.Equals("Exclud");//false bool booTest4 = words.Equals("Exclud");//false bool booTest5 = test3.Equals("Exclud");//false
12
3752
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 and hence it is possible to do: txt += "foo bar";
16
1873
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?" Ok. It's a broad, and maybe a very silly question to ask, but still. I mean, what good has it brought to us? What advantages immutable strings have against mutable ones?
11
5300
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 resize an array size in .NET ? I guess it's not possible to do that. Thanks
0
8788
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8697
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9290
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9159
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7925
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3151
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2508
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2097
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.