Replace single character at given position

M

Martin Kulas

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
 
B

Bjoern Schliessmann

Martin said:
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
 
B

bearophileHUGS

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
 
L

Larry Bates

Martin said:
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
 
R

Roberto Bonvallet

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 :)
 
M

Magnus Lycka

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.

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.
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top