473,757 Members | 3,768 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replace Several Items

I wish to replace several characters in my string to only one.
Example, "-", "." and "/" to nothing ""
I did like that:
my_string = my_string.repla ce("-", "").replace("." , "").replace ("/",
"").replace(")" , "").replace("(" , "")

But I think it's a ugly way.

What's the better way to do it?
Aug 13 '08
15 1585
On Aug 14, 8:50 am, Wojtek Walczak
<gmin...@nie.ma .takiego.adresu .w.sieci.plwrot e:
Dnia Thu, 14 Aug 2008 00:31:00 +0200, Fredrik Lundh napisa³(a):
> if ch in my_string:
my_string = my_string.repla ce(ch, "")
>on representative data.
I don't have to, I can anticipate the results.
Chances are that you're wrong.

At the moment my average is about 0.75 of mistake per
post on comp.lang.pytho n (please, bare with me ;-)).
I strongly believe that the statement I made above won't
make this number rise.
Meta-mistake: Playing poker with the effbot. If he says diffidently
that he'll raise you a dime, it means he's holding five aces :-)

Clue: The effbot was the original author of the modern (Python 1.6?)
version of the re module.

HTH,
John
Aug 14 '08 #11
On Wed, 13 Aug 2008 22:50:29 +0000, Wojtek Walczak wrote:
Dnia Thu, 14 Aug 2008 00:31:00 +0200, Fredrik Lundh napisa³(a):
>>> if ch in my_string:
my_string = my_string.repla ce(ch, "")

on representative data.

I don't have to, I can anticipate the results.

Chances are that you're wrong.

At the moment my average is about 0.75 of mistake per post on
comp.lang.pytho n (please, bare with me ;-)). I strongly believe that the
statement I made above won't make this number rise.

:)


Okay, is this going to be one of those things where, no matter what the
benchmarks show, you say "I was right, I *did* anticipate the results. I
just anticipated them correctly/incorrectly."?

If so, you get an A+ in pedantry and F- in usefulness *wink*

In full knowledge that Python is relatively hard to guess what is fast
compared to what is slow, I'll make my guess of fastest to slowest:

1. repeated replace
2. repeated use of the form
"if ch in my_string: my_string = my_string.repla ce(ch, "")
3. re.sub with literal replacement
4. re.sub with callback (lambda m: "")
Results to follow.
--
Steven
Aug 14 '08 #12
Steven D'Aprano wrote:
While I'm gratified that my prediction was so close to the results I
found, I welcome any suggestions to better/faster/more efficient code.
more things to try:
code tweaks:

- Factor out the creation of the regular expression from the tests:
"escape" and "compile" are relatively expensive, and neither throw-away
code (using the RE function forms) nor production code will end up doing
them both for each string.

- Same w. the translation table for "translate"

- Use Unicode strings instead of byte strings (we're moving towards 3.0,
after all).

test data variations:

- Try dropping the number of actual replacements and see what happens --
if you're escaping user-provided data (e.g. HTML), for example, it's not
that unlikely that you end up doing only a few replacements for each
string you're processing, or no replacements at all.

- Also try shorter and longer strings ("human-sized" data is often
provided in shorter chunks than 216 characters per string; the typical
size and distribution depends on your actual application, of course).

Unicode will affect translate more than the others; the last two will
most likely affect in-replace instead (that approach gets faster the
shorter the strings are, and the fewer calls to replace that you
actually end up doing).

Finally, if you want the sub-lambda form to look better, try inserting a
character before or after each special character using a template string
or a lambda (e.g. a backslash).

</F>

Aug 14 '08 #13
John Machin wrote:
Clue: The effbot was the original author of the modern (Python 1.6?)
version of the re module.
And the author of the "in" and "replace" implementations in Python 2.5.

</F>

Aug 14 '08 #14
On 2008-08-13 23:54, John Krukoff wrote:
On Wed, 2008-08-13 at 09:39 -0700, gjhames wrote:
>I wish to replace several characters in my string to only one.
Example, "-", "." and "/" to nothing ""
I did like that:
my_string = my_string.repla ce("-", "").replace("." , "").replace ("/",
"").replace(") ", "").replace("(" , "")

But I think it's a ugly way.

What's the better way to do it?
--
http://mail.python.org/mailman/listinfo/python-list


The maketrans interface is a bit clunky, but this is what
string.translat e is best at:

>>import string
>>>'-./other'.translat e( string.maketran s( '', '' ), '-./' )
'other'

It'd be interesting to see where it falls in the benchmarks, though.

It's worth noting that the interface for translate is quite different
for unicode strings.
Right. Unicode .translate() uses a dictionary for defining the
mapping.

Another approach is to use the re module:
>>import re
re.sub('[-./()]', '', '-./other')
'other'

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source (#1, Aug 14 2008)
>>Python/Zope Consulting and Support ... http://www.egenix.com/
mxODBC.Zope.D atabase.Adapter ... http://zope.egenix.com/
mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
_______________ _______________ _______________ _______________ ____________

:::: Try mxODBC.Zope.DA for Windows,Linux,S olaris,MacOSX for free ! ::::
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
Aug 14 '08 #15
On 14 Aug 2008 01:54:55 GMT, Steven D'Aprano wrote:
>>>I don't have to, I can anticipate the results.

Chances are that you're wrong.

At the moment my average is about 0.75 of mistake per post on
comp.lang.pyth on (please, bare with me ;-)). I strongly believe that the
statement I made above won't make this number rise.
Okay, is this going to be one of those things where, no matter what the
benchmarks show, you say "I was right, I *did* anticipate the results. I
just anticipated them correctly/incorrectly."?
Don't count on it. I never really cared about being right or wrong
and I am not one of those guys who are trying to prove something
that actually makes no difference at all. Nice tests, though :)
--
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
Aug 14 '08 #16

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

Similar topics

6
2255
by: andrea.gavana | last post by:
Hello NG, probably this is a basic question, but I'm going crazy... I am unable to find an answer. Suppose that I have a file (that I called "Errors.txt") which contains these lines: MULTIPLY 'PERMX' @PERMX1 1 34 1 20 1 6 / 'PERMX' @PERMX2 1 34 21 41 1 6 / 'PERMX' @PERMX3 1 34 1 20 7 14 /
7
2243
by: ajikoe | last post by:
Hello, I would like to replace string with different values, For example : source = 'kode1 bla bla kode1 bla kode1' I have a list with each member will replace each of kode1. L = So the new source will become: newsource = '11 bla bla 22 bla 33'
1
2890
by: Luke Dalessandro | last post by:
I have an application where there is a primary XML data file. I'll use the following as an example: <data> <item id="a"> <name>A</name> <price>$10</price> </item> <item id="b"> <name>B</name>
4
10200
by: Jane Doe | last post by:
Hi, I need to search and replace patterns in web pages, but I can't find a way even after reading the ad hoc chapter in New Rider's "Inside JavaScript". Here's what I want to do: function filter() { var items = new Array("John", "Jane");
0
857
by: **Developer** | last post by:
Been experimenting with menu items merging and it seems to me that all I need is Replace and Remove If the item is not already there Add, Merge and Replace all seem to add it. If it is already there, Replace and Merge seem to do the same thing (I normally wouldn't use Add if it might be there because I wouldn't want two). So why can't I always use Replace in place of Merge and Add? I figure there is a reason but haven't found it yet!
1
2287
by: mimenko | last post by:
Hello, I'd want to show and hide the same icons (pictures) on a web page that contains several icons. Some are identical, some are different (for ex : 3 items "A", 4 items "B", 2 items "C"). Is it possible to make radio buttons or check cases to show all the same items on the page (and to hide them if no action is done on the buttons) ? (I'd want one button for items "A", one another for items "B", and a third for items "C"). All the items...
4
1920
by: ds4ff1z | last post by:
Hello, i'm looking to find and replace multiple characters in a text file (test1). I have a bunch of random numbers and i want to replace each number with a letter (such as replace a 7 with an f and 6 with a d). I would like a suggestion on an a way to do this. Thanks
1
1138
by: Dinis Correia | last post by:
Hi all, How can I replace an inherited member name? I've built a class that inherits from KeyedCollection(Of ..., ...). I would like to replace base class Items property with Fields property. Is this possible? TIA, DC
1
3392
by: neovantage | last post by:
Hey all, I am using a PHP script which creates headings at run time in a sense at page execution. I am stuck a with a very little problem which i am sure i will have the solution from experts. The problem is when it creates transparent PNG format image then and it pixel ate the image. e.g. If i am using a gradient in background then it vary in color range. Now when i used that php script it generates image successfully but it pixel ate...
0
9487
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
9904
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9735
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
8736
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
7285
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
6556
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
5168
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3828
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

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.