473,509 Members | 2,526 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 2505
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
3270
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
34075
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
9616
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
6138
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
3356
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
5463
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
2401
by: Umesh | last post by:
Do you have any answer to it? thx.
1
13647
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
2475
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
3262
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...
0
7233
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,...
0
7135
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...
0
7410
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...
1
7067
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...
0
7505
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...
0
4729
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...
0
3215
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1570
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 ...
0
440
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...

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.