473,394 Members | 1,810 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,394 software developers and data experts.

Modify a string's value

Hi everyone,

I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?

Thanks,
Sebastian
Jul 15 '08 #1
8 1717
s0****@gmail.com writes:
I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?
If there were, it would not be immutable. The 'str' type has only
immutable values.

You could implement your own string type, and have it allow mutable
values. You'd have to take care of creating those values explicitly,
though.

--
\ “Pinky, are you pondering what I'm pondering?” “I think so, |
`\ Brain, but shouldn't the bat boy be wearing a cape?” —_Pinky |
_o__) and The Brain_ |
Ben Finney
Jul 15 '08 #2
Sebastian:
I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?
No, but you can use other kind of things:
>>s = "hello"
sl = list(s)
sl[1] = "a"
sl
['h', 'a', 'l', 'l', 'o']
>>"".join(sl)
'hallo'
>>from array import array
sa = array("c", s)
sa
array('c', 'hello')
>>sa[1] = "a"
sa
array('c', 'hallo')
>>sa.tostring()
'hallo'

Bye,
bearophile
Jul 15 '08 #3


s0****@gmail.com wrote:
Hi everyone,

I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?
In 3.0, ascii chars and encoded unicode chars in general can be stored
in a mutable bytearray.

Jul 15 '08 #4
On Jul 15, 3:06*pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
s0s...@gmail.com writes:
I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?

If there were, it would not be immutable. The 'str' type has only
immutable values.

You could implement your own string type, and have it allow mutable
values. You'd have to take care of creating those values explicitly,
though.
You could write a C extension which modifies strings, but that would
be a Bad Idea.
Jul 15 '08 #5
s0****@gmail.com wrote:
Hi everyone,

I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?

Thanks,
Sebastian
Why would you care? Just create a new string (with the changed contents) and
let garbage collection take care of the old one when all the references to it
have gone away. Since these types of questions seem to appear almost every day
on this list, this Python stuff is so much different than old languages people
have hard time making the conceptual "jump". You can basically quite worrying
about how/where things are stored, they just are.

-Larry
Jul 15 '08 #6
On Jul 15, 6:46 pm, Larry Bates <larry.ba...@websafe.com`wrote:
s0s...@gmail.com wrote:
Hi everyone,
I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?
Thanks,
Sebastian

Why would you care? Just create a new string (with the changed contents) and
let garbage collection take care of the old one when all the references to it
have gone away. Since these types of questions seem to appear almost every day
on this list, this Python stuff is so much different than old languages people
have hard time making the conceptual "jump". You can basically quite worrying
about how/where things are stored, they just are.
Thanks for the reply. It's not that I'm having a hard time learning
Python. I've been programming it for some time. I just came across
this unusual situation where I'd like to modify a string passed to a
function, which seems impossible since Python passes arguments by
value. (Whereas in C, you'd customarily pass a pointer to the first
character in the string.)

I was playing around trying to simulate C++-like stream operations:

import sys
from os import linesep as endl

class PythonCout:
def __lshift__(self, obj):
sys.stdout.write(str(obj))
return self

def __repr__(self):
return "<cout>"

cout = PythonCout()
cout << "hello" << endl

But then trying to simulate cin:

class PythonCin:
def __rshift__(self, string):
string = sys.stdin.readline() # which doesn't make sense

line = ""
cin >line

And there goes the need to modify a string. :)

Jul 16 '08 #7
s0****@gmail.com writes:
I just came across this unusual situation where I'd like to modify a
string passed to a function
Again: Why? The normal way to do this is to create a new string and
return that.
which seems impossible since Python passes arguments by value.
No, Python passes arguments by reference
<URL:http://effbot.org/zone/python-objects.htm>.

--
\ “For of those to whom much is given, much is required.” —John |
`\ F. Kennedy |
_o__) |
Ben Finney
Jul 16 '08 #8
On Jul 15, 11:55 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
s0s...@gmail.com writes:
I just came across this unusual situation where I'd like to modify a
string passed to a function

Again: Why? The normal way to do this is to create a new string and
return that.
<snip>

Yes, usually, but that won't work in this case (look at my previous
post around the 'cin >line' line). This is what I came up with:

class StreamLineBuffer:
def __init__(self):
self.buf = ""

def __rrshift__(self, stream):
self.buf = stream.readline()

def __str__(self):
return self.buf

cin = sys.stdin
buf = StreamLineBuffer()

cin >buf
line = str(buf)

Works like a charm :)

Jul 16 '08 #9

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

Similar topics

1
by: jwpioneer | last post by:
I have a need within an application to modify the path environment variable, as I need to find specific directories and remove them. I use the following code to do this: RegistryKey rkey = ...
4
by: Markus Dehmann | last post by:
I guess this is a kind of newbie question (since most pointer questions are newbie questions). In the program below, modify(string* s) is supposed to change the content that s points to. But the...
1
by: Glenn | last post by:
Searching through google groups, I have not found anyone able to modify the query string of a request. I was hoping to make the query string as short as possible so that a search with many...
28
by: Charles Sullivan | last post by:
I'm working on a program which has a "tree" of command line arguments, i.e., myprogram level1 ]] such that there can be more than one level2 argument for each level1 argument and more than one...
4
by: Vladimir C. | last post by:
Hashtable map = new Hashtable(); map = 10; map = 20; foreach(DictionaryEntry e in map) { e.Value = 100; Console.WriteLine("{0}: {1}", key, map); }
1
by: Fabrice | last post by:
Hello Is it possible to modify CommandArgument property of a LinkButton from vb class (code behind). So, this is my control in my .aspx page : <asp:LinkButton id="strTd"...
4
by: Bob | last post by:
Hi all, I'm trying to import data, modify the data then insert it into a new table. The code below works fine for it but it takes a really long time for 15,000 odd records. Is there a way I...
2
by: wizofaus | last post by:
Given the following code: public class Test { static unsafe void StringManip(string data) { fixed (char* ps = data) ps = '$'; }
6
by: Ramesh | last post by:
Hello, I am using the ofstream class to create a text file with keys and values like: Key1=Value10 Key2=Value15 Key3=Value20 In case I need to set a new value for Key2, say value50 - I am...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.