473,539 Members | 9,333 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 39208
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
47794
by: Pikkel | last post by:
i'm looking for a way to replace special characters with characters without accents, cedilles, etc.
5
7296
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 i = s.find(exist, 0); i != string::npos; i = s.find(foo, i)) { s.replace(i, foo.size(), bar);
1
2173
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> Organization: Texas Instruments Newsgroups: alt.comp.lang.learn.c-c++ I'm trying to remove the \n from a string. If I just simply locate teh char and replace it with \0 then the destructor should only...
8
4021
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 string. I thought this would be simple but I had problems getting my algorithm to work and in order to help me find the solution I decided to print each line to screen as I read them. Then, to my...
14
2022
by: inpuarg | last post by:
I want to find a & character using Regex. But not && How can i manage this in c# Quickfind window ? -------------------------------------------------- ne kadar yaşarsan yaşa sevdiğin kadardır ömrün :( --------------------------------------------------
8
4483
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 replaced select "name", "vorname", "userid", "passwort" from "users" order by "users"
23
13414
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 = "\\wusais\Intranets\Intranets\fpdb\pdf\weinig\00505882.pdf"; $new = preg_replace("\\", "\\\", "$var"); ?> Code above produces the following error:
6
6789
by: Gabriel | last post by:
Hello, I do this : s = Environment.CurrentDirectory; s = s.Replace("\\", @"\"); Environment.CurrentDirectiry return a path like this C:\\....\\....\\..... I'd like replace the \\ by \, but the code I use not work. Any idea ? Best Regards,
10
18613
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 Replace method would be overloaded with an index parameter with which you can write wanted character at that position. But no, Replace method only allows replacing one known character with another. The...
0
7368
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...
0
7311
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...
0
7706
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...
1
7297
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7655
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3361
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1774
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
1
934
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
601
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...

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.