473,555 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Modify one character in a string

mp
X-No-Archive
How do I go about modifying one character in a string elegantly?
In other words, I want a function that will change 'aaaa' to 'aaza',
given the index 2 of the character in the string.

Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?

Thanks
MP

May 25 '06 #1
7 2256
"mp" <ma*********@em ail.com> writes:
How do I go about modifying one character in a string elegantly?
In other words, I want a function that will change 'aaaa' to 'aaza',
given the index 2 of the character in the string.
Ehh, there are various ways, all ugly.
x = 'aaaa'
y = x[:2] + 'z' + x[3:]
is the most direct.
Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?


You mean you want to change a character in a file?

f = open(file, 'r+') # open for reading and writing
f.seek(2) # position at character index 2
f.write('z') # put a 'z' there
f.seek(0) # rewind
print f.read() # get entire contents and see the change

You could also look at the mmap module.
May 25 '06 #2

mp wrote:
X-No-Archive
How do I go about modifying one character in a string elegantly?
In other words, I want a function that will change 'aaaa' to 'aaza',
given the index 2 of the character in the string.

Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?

Thanks
MP


Technically you can't - strings are immutable. If you use the StringIO
module then you can
use a common approach between 'strings' in memory, and files, using
seek and write.

All the best,

Keir.

May 25 '06 #3
"mp" <ma*********@em ail.com> wrote:
X-No-Archive
How do I go about modifying one character in a string elegantly?
In other words, I want a function that will change 'aaaa' to 'aaza',
given the index 2 of the character in the string.
Strings are immutable, so you can't change a string. The best you can do
is create a new string from the old one. Something like:
old = 'aaaa'
new = old[:2] + 'z' + old[3:]
print new

aaza

or a few variations on that theme.
Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?


This is a much more complicated question, because it depends on the details
of the operating system you're using. On Unix, you can seek to a specific
place in a file, write a single character, seek to EOF, and you've done an
in-place single character edit of the file. I don't know if that works on
other OS's or not.
May 25 '06 #4
mp wrote:
X-No-Archive
How do I go about modifying one character in a string elegantly?
In other words, I want a function that will change 'aaaa' to 'aaza',
given the index 2 of the character in the string.

Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?

Thanks
MP

IMHO the most elegant method is something like:

def switchchar(srcs tring, position, character):
b=list(srcstrin g)
b[2]=character
return ''.join(b)

You should open file in binary 'b' mode. Use .seek() method
to seek to the character you want to replace. use .write() method
to write one character.

-Larry
May 25 '06 #5
Larry Bates <la*********@we bsafe.com> writes:
IMHO the most elegant method is something like:

def switchchar(srcs tring, position, character):
b=list(srcstrin g)
b[2]=character
return ''.join(b)


If the strings or large or you're doing it a lot, the array module is
likely more efficient.
May 25 '06 #6
In <ro************ ***********@rea der1.panix.com> , Roy Smith wrote:
Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?


This is a much more complicated question, because it depends on the details
of the operating system you're using. On Unix, you can seek to a specific
place in a file, write a single character, seek to EOF, and you've done an
in-place single character edit of the file.


Why seeking to EOF after writing the byte?

Ciao,
Marc 'BlackJack' Rintsch
May 26 '06 #7
Marc 'BlackJack' Rintsch wrote:
In <ro************ ***********@rea der1.panix.com> , Roy Smith wrote:
Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?

This is a much more complicated question, because it depends on the details
of the operating system you're using. On Unix, you can seek to a specific
place in a file, write a single character, seek to EOF, and you've done an
in-place single character edit of the file.


Why seeking to EOF after writing the byte?


Because some operating systems may create an EOF (thus truncating the
file) after a write, close sequence.

--Scott David Daniels
sc***********@a cm.org
May 26 '06 #8

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

Similar topics

4
4234
by: sinister | last post by:
Is it possible to modify a string in one place using an indexing operator and an assignment statement? E.g.: $s = "1234567890"; $s = "d"; // $s is now "12345d7890" According to _PHP Bible_ (2nd ed., p.175), this kind of syntax can work , but is undocumented and, moreover, appears to be discouraged because "almost all PHP string...
28
12523
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 level3 argument for each level2 argument, etc. Suppose I code it similar to this fragment: int main( int argc, char *argv ) {
13
2499
by: baumann.Pan | last post by:
when define char *p = " can not modify"; p ='b' ;is not allowed, but if you declare p as char p = "can modify"; p = 'b'; is ok? why?
11
1810
by: Zeng | last post by:
Hello, Is it true that in C# we can't modify directly a character in a string? I can't find the method anywhere. I would expect something like this should work,but it doesn't string myStr = "blah'; myStr = 'e';
0
2383
by: richardkreidl | last post by:
I have the following hash script that I use to compare two text files. 'Class Public Class FileComparison Public Class FileComparisonException Public Enum ExceptionType U 'Unknown A 'Add D 'Delete
1
1196
by: news | last post by:
Hello, Can someone please help to modify my string from the input value in my inputbox!? Example from my input box: - c:\test\att beställa.txt (swedish character) This is what I need: - c:\test\att_bestalla.txt I need to replace the "space" with "_" and replace the swedish character "ä"
4
7666
by: libadmin | last post by:
I have a large database (for me) containing about 23,000 records and I need to add a single digit (the number 8) to all data currently in a specific field.. This field contains numbers already that are 8 characters and I need to change them to nine by adding a #8 to the beginning of each entry... Any easy way of doing that?? \Bob
8
1730
by: s0suk3 | last post by:
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
4
4171
Mighty Mackinac
by: Mighty Mackinac | last post by:
Hi all, I am trying to write a program that can encrypt and decrypt files using an extremely basic encryption scheme. Here's a list of what I still need: 1. Read scheme from file to be applied to input file 2. Modify input to match the scheme 3. Write output to new file My first actual question is what is the code to read two different...
0
7547
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
8060
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
7588
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
6176
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5452
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5171
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2037
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
1159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
865
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.