469,289 Members | 2,330 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,289 developers. It's quick & easy.

Replace single character at given position

Hello!

How do I replace a single character in a string at a given position?

From programming languages like C I expect something like that:
>>idx = 1
s1 = "pxthon"
s1[idx] = 'y'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment

It does not work :-(

My second attempt succeeds:
>>s1 = s1[0:idx] + 'y' + s1[idx+1:]
s1
'python'
Is this a typical approach in Python to replace one character
in a string? Are there better (faster) ways to achieve my goal?
I have looked through the methods of type ``string''
but I have not found any appropriate method or function.

Thanks in advance,
Martin

Sep 19 '06 #1
5 38802
Martin Kulas wrote:
From programming languages like C I expect something like that:
>>>idx = 1
s1 = "pxthon"
s1[idx] = 'y'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment

It does not work :-(
Yes, Python strings are immutable.
Is this a typical approach in Python to replace one character
in a string? Are there better (faster) ways to achieve my goal?
Is speed *really* your primary goal? :)

You could also convert the string to a list, do the changes, and
convert back.

Regards,
Björn

--
BOFH excuse #259:

Someone's tie is caught in the printer, and if anything else gets
printed, he'll be in it too.

Sep 19 '06 #2
Martin Kulas:
Are there better (faster) ways to achieve my goal?
I have looked through the methods of type ``string''
but I have not found any appropriate method or function.
Python strings are immutable, so you can't modify them, so you can't
find methods to change them. I agree that sometimes this is a pain,
expecially if you come from languages where strings are mutable.

The best solution may seem the strangest, that is "to not need to do
that". Often with python you can use different (higher level) code that
doesn't require to change many single chars inside a string.

A second way is to use a list of strings with len=1. Like this:
>>idx = 1
s1 = "pxthon"
l1 = list(s1)
l1[idx] = 'y'
.... more processing on the elements of l1, then at the end:
>>"".join(l1)
'python'

Note that structures like that l1 require a lot of memory.
A third solution is to use an array of chars:
>>from array import array
a1 = array("c", s1)
a1
array('c', 'pxthon')
>>a1[idx] = "y"
a1
array('c', 'python')
>>a1.tostring()
'python'

Bye,
bearophile

Sep 19 '06 #3
Martin Kulas wrote:
Hello!

How do I replace a single character in a string at a given position?

From programming languages like C I expect something like that:
>>>idx = 1
s1 = "pxthon"
s1[idx] = 'y'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment

It does not work :-(

My second attempt succeeds:
>>>s1 = s1[0:idx] + 'y' + s1[idx+1:]
s1
'python'
Is this a typical approach in Python to replace one character
in a string? Are there better (faster) ways to achieve my goal?
I have looked through the methods of type ``string''
but I have not found any appropriate method or function.

Thanks in advance,
Martin
You can do this:

s1=s1.replace('x','y', 1) # Only replace the first x with y

or

s1l=list(s1)
s1l[1]='y'
s1=''.join(s1l)

or your method of using slices.

All depends on what you want to do. Quite often you use
..replace() method so you don't have to worry with the index.

-Larry Bates
Sep 19 '06 #4
be************@lycos.com wrote:
Martin Kulas:
>Are there better (faster) ways to achieve my goal?
I have looked through the methods of type ``string''
but I have not found any appropriate method or function.
[...]
A second way is to use a list of strings with len=1. Like this:
>>>idx = 1
s1 = "pxthon"
l1 = list(s1)
l1[idx] = 'y'
... more processing on the elements of l1, then at the end:
>>>"".join(l1)
'python'
There is a MutableString class that would be a better approach:
http://docs.python.org/lib/module-UserString.html

Anyway, I bet that what Martin wants to do can be done by using only string
methods :)
--
Roberto Bonvallet
Sep 20 '06 #5
Larry Bates wrote:
>How do I replace a single character in a string at a given position?
You can't. Strings can't be mutated in Python how ever hard you try.
The string type is immutable. (Of course, I suspect you can write a
horrible C extension that would help you cheat. Yuk!)

You need to create a *new* string object with the properties you like.
This is what you do below. As soon as you use "s1=...", you are
rebinding "s1" to a (typically) different string object than it was
bound to before.

If you think about this, it will probably also answer the "does Python
use call by reference or call by value" questions that will eventually
pop up in your head if you come from C.
>From programming languages like C I expect something like that:
What you need to realize is that objects and assignments are
different in Python and in C. In C, "a=x" basically means "put
the value identified by x in the location defined by a". In
Python, "a=x" basically means "bind the name a to the object
identified by x". See http://pyref.infogami.com/naming-and-binding
You can do this:

s1=s1.replace('x','y', 1) # Only replace the first x with y

or

s1l=list(s1)
s1l[1]='y'
s1=''.join(s1l)
Both these examples creates new string objects and rebind the
name s1 to these new objects. In other words, if you had "s2=s1"
on a previous line, the expression "s1==s2" will be false after
the code above has been executed.
Sep 27 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by mr h q | last post: by
1 post views Thread by Billy N. Patton | last post: by
14 posts views Thread by inpuarg | last post: by
8 posts views Thread by Lothar Behrens | last post: by
23 posts views Thread by dkirkdrei | last post: by
6 posts views Thread by Gabriel | last post: by
1 post views Thread by CARIGAR | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.