472,334 Members | 2,232 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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 39097
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Pikkel | last post by:
i'm looking for a way to replace special characters with characters without accents, cedilles, etc.
5
by: mr h q | last post by:
Hi all, i want to replace $ to \$ so linux can work with paths and filenames that contain $. I wrote the following code for(string::size_type...
1
by: Billy N. Patton | last post by:
-------- Original Message -------- Subject: <string>.replace Date: Fri, 15 Oct 2004 11:07:19 -0500 From: Billy N. Patton <b-patton@ti.com>...
8
by: Eric Lilja | last post by:
Hello, I had what I thought was normal text-file and I needed to locate a string matching a certain pattern in that file and, if found, replace that...
14
by: inpuarg | last post by:
I want to find a & character using Regex. But not && How can i manage this in c# Quickfind window ?...
8
by: Lothar Behrens | last post by:
Hi, I have selected strtok to be used in my string replacement function. But I lost the last token, if there is one. This string would be...
23
by: dkirkdrei | last post by:
I am having a bit of trouble trying to double up on slashes in a file path. What I am trying to do is very similar to the code below: <? $var =...
6
by: Gabriel | last post by:
Hello, I do this : s = Environment.CurrentDirectory; s = s.Replace("\\", @"\"); Environment.CurrentDirectiry return a path like this...
10
by: Lonifasiko | last post by:
Hi, Just want to replace character at index 1 of a string with another character. Just want to replace character at that position. I thought...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

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.