472,805 Members | 834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

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 2444
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, "replacements 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
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....
4
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...
12
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(" &...
16
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 =...
21
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...
5
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>...
18
by: Umesh | last post by:
Do you have any answer to it? thx.
1
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...
2
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...
3
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth

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.