473,670 Members | 2,551 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String replace with return value?

How can I do a "".replace operation which tells me if anything was
actually replaced?

Right now I am doing something like:

if searchTerm in text:
text = text.replace( searchTerm, 'other' )

But to me this seems inefficient since the 'in' operation will search
through the whole string, and then the 'replace' will as well.

The strings are quite large, they're whole web pages. Thanks for any help.

Roose
Jul 18 '05 #1
5 2515
On Mon, Oct 11, 2004 at 09:47:48AM +0000, Roose wrote:
How can I do a "".replace operation which tells me if anything was
actually replaced?
You could compare the strings from before and after the replacement.
Right now I am doing something like:

if searchTerm in text:
text = text.replace( searchTerm, 'other' )

But to me this seems inefficient since the 'in' operation will search
through the whole string, and then the 'replace' will as well.
Yep. Why not just omit the check and just do the replacement?
The strings are quite large, they're whole web pages. Thanks for
any help.


Then I'd suggest to eventually switch to an existing templating
solution for HTML.

My guess is, however, that you're relatively new to Python. And in
this case, reinventing the wheel a few times is a good way to learn
the language and the libraries. We all did that ;-)

For your particular question, you can also use the re module to
perform string substitutions. And then, there's re.subn or the subn
method of regular expression objects, which will return both the
modified string and the number of substitutions.

Here's a short example for the subn method:

############### ############### ###############
import re
import time

modifiedRe = re.compile(r"\$ modifieddate")

text = "this webpage was last modified on $modifieddate"

print text
text, replacements = modifiedRe.subn (time.asctime() , text)
print text
print replacements, "replacemen ts made"
############### ############### ###############

HTH,

-- Gerhard
Jul 18 '05 #2
Roose wrote:
How can I do a "".replace operation which tells me if anything was
actually replaced?

Right now I am doing something like:

if searchTerm in text:
text = text.replace( searchTerm, 'other' )


Try:

newtext = oldtext.replace (searchTerm, 'other')
if newtext is oldtext:
print "nothing changed"
else:
print "modified text"

You can almost certainly get away with using 'is' here since if replace
doesn't replace anything it simply returns the original string (this is an
implementation detail though, I don't know that there is a cast iron
guarantee that a future implementation won't copy the string if it hasn't
changed, although it would be pretty perverse if it did.)
Jul 18 '05 #3
Duncan Booth wrote:
How can I do a "".replace operation which tells me if anything was
actually replaced?
Right now I am doing something like:

if searchTerm in text:
text = text.replace( searchTerm, 'other' )


Try:

newtext = oldtext.replace (searchTerm, 'other')
if newtext is oldtext:
print "nothing changed"
else:
print "modified text"

You can almost certainly get away with using 'is' here since if replace
doesn't replace anything it simply returns the original string


depends on how you define "if anything was actually replaced", of course:
mytext = "hello" mytext is mytext.replace( "l", "l") False mytext == mytext.replace( "l", "l") True
mytext is mytext.replace( "x", "x") True mytext == mytext.replace( "x", "x")

True

</F>

Jul 18 '05 #4
Gerhard Haering wrote:
On Mon, Oct 11, 2004 at 09:47:48AM +0000, Roose wrote:
How can I do a "".replace operation which tells me if anything was
actually replaced?

You could compare the strings from before and after the replacement.

Right now I am doing something like:

if searchTerm in text:
text = text.replace( searchTerm, 'other' )

But to me this seems inefficient since the 'in' operation will search
through the whole string, and then the 'replace' will as well.

Yep. Why not just omit the check and just do the replacement?

I thought of that, but don't you see, that's pretty much the same thing.
It's a question of doing an 'in' and a replace vs. a compare and a
replace. Both in and equality comparison are linear operations, so
choosing over the other doesn't really matter. A speedup can still be
obtained by traversing the string once instead of twice.

Now, the person who suggested using 'is' (which is constant time) was
onto something, but alas replace doesn't work like that. As someone
demonstrated, it returns a new string in any case.


The strings are quite large, they're whole web pages. Thanks for
any help.

Then I'd suggest to eventually switch to an existing templating
solution for HTML.


That doesn't apply, since I'm not generating web pages. I'm
transforming existing ones in a spider kind of program.
For your particular question, you can also use the re module to
perform string substitutions. And then, there's re.subn or the subn
method of regular expression objects, which will return both the
modified string and the number of substitutions.


Thank you, that's just what I was looking for.

Roose
Jul 18 '05 #5
Roose wrote:
I thought of that, but don't you see, that's pretty much the same thing.
It's a question of doing an 'in' and a replace vs. a compare and a
replace. Both in and equality comparison are linear operations, so
choosing over the other doesn't really matter. A speedup can still be
obtained by traversing the string once instead of twice.

Now, the person who suggested using 'is' (which is constant time) was
onto something, but alas replace doesn't work like that. As someone
demonstrated, it returns a new string in any case.


No, it only returns a new string if it actually does a replacement.

Frederick Lundh confused the issue by pointing out that a replace can do a
replacement on a string but leave it unchanged. Provided you can guarantee
that the original string and replacement string are different this won't
matter.

To keep Frederick happy, you could change my example to:

if searchTerm == replacement:
newtext = oldtext
else:
newtext = oldtext.replace (searchTerm, replacement)

if newtext is oldtext:
print "nothing changed"
else:
print "modified text"

I will be surprised though if the overhead of comparing strings using '=='
even if they are large web pages if measurable in terms of either server
loading or time to retrieve a page.
Jul 18 '05 #6

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

Similar topics

5
3284
by: nboutelier | last post by:
Scenario: you enter "foo bar" into a text field... Is it possible through javascript to select/highlight just "foo"? formObject.select() selects all. I need to select only part of the string. -Nick
4
34091
by: Locusta | last post by:
Hello, I have been struggeling for replacing a string in a string. The snippet from the program below replaces the <, & and > with the XML equivalent values. In the program, I allocate space for storing the XML value. This makes my life a bit easier since I can easilly reallocate space to include the required new space.
12
9631
by: Jeff S | last post by:
In a VB.NET code behind module, I build a string for a link that points to a JavaScript function. The two lines of code below show what is relevant. PopupLink = "javascript:PopUpWindow(" & Chr(34) & PopUpWindowTitle & Chr(34) & ", " & Chr(34) & CurrentEventDetails & ")" strTemp += "<BR><A HREF='#' onClick='" & PopupLink & "'>" & EventName & "</A><BR>" The problem I have is that when the string variables or contain a string with an...
16
6157
by: BBM | last post by:
This is so bizarre I hesitate to post it, but I need to get this working. My code looks like this... Private Const cmdTestResourcesSel = "SELECT * FROM TResources" & _ " WHERE Scenario = @Scenario" Dim cmdstr as String cmdstr = cmdTestResourcesSel
21
3383
by: gary | last post by:
How would one make the ECMA-262 String.replace method work with a string literal? For example, if my string was "HELLO" how would I make it work in this instance. Please note my square brackets are not regular expression syntax. Thanks,
5
5477
by: int main(void) | last post by:
Hi all, Following is my attempt to write a string search and replace function. #include <stdio.h> #include <stdlib.h> #include <string.h> /*------------------------------------------------------------------------------------------- | Function name : strrep
18
2426
by: Umesh | last post by:
Do you have any answer to it? thx.
1
13689
by: Gene Kelley | last post by:
This has got to be an easy one, but I'm just not getting it. The following function (below) returns name=value pairs from URL queries (GET). All is working as expected, but I am trying to figure out how to remove the + (plus signs) from the values that contain spaces. I'm trying to use the String Object's replace() method to accomplish this. This is what I've tried so far along with the results:
2
2484
by: kevin.eugene08 | last post by:
hi all, i'm trying to replace a string with known "tokens" with values -- and am not sure how to do this effectively. Since i don't know the size of the string containing the tokens to be replaced, i can't make a buffer -- hence i thought of using malloc() -- is what i have below effective? it doesn't seem to work though - the returned string just returns the substituted part. Any thoughts / comments are welcomed.
3
3273
by: kronus | last post by:
I'm receiving an xml file that has a child called modified and it represents a date value in the form of a string -- Nov 14, 2008 -- and in my app, I have items associated with each object and I'm trying to sort them by the date modified field. So what's the problem, right? Well, obviously Sep 14, 2008 is before Nov 14, 2008, but when doing a sort process, ActionScript will come back with Nov coming before Sep, because N comes before S in...
0
8466
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8901
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8659
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7412
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6212
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5683
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4388
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2037
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1791
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.