473,729 Members | 2,344 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 #1
15 1583
gjhames:
What's the better way to do it?
Better is a relative term. If with better you mean "faster" (in some
circumstances), then the translate method is your friend, as you can
see its second argument are the chars to be removed. As first argument
you can use something like:
"".join(map(chr , xrange(256)))
If your strings are unicode you will need something different (a dict
with Null values for the key chars you want to remove).

Bye,
bearophile
Aug 13 '08 #2
I tend to use the re module like so :

import re
my_string = re.sub('[\-,./]','',my_string)
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 #3
Dnia Wed, 13 Aug 2008 09:39:53 -0700 (PDT), gjhames napisa³(a):
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?
The regular expression is probably the best way to do it,
but if you really want to use replace, you can also use
the replace method in loop:
>>somestr = "Qwe.Asd/Zxc()Poi-Lkj"
for i in '-./()':
.... somestr = somestr.replace (i, '')
....
>>somestr
'QweAsdZxcPoiLk j'
>>>

Next step would be to define your own replacing function:

def my_replace(myst r, mychars, myrepl):
"""Replace every character from 'mychars' string with 'myrepl' string
in 'mystr' string.

Example:

my_replace('Qwe .Asd/Zxc(', './(', 'XY') -'QweXYAsdXYZxcX Y'"""

for i in mychars:
mystr = mystr.replace(i , myrepl)

return mystr
--
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
Aug 13 '08 #4
Wojtek Walczak 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?

The regular expression is probably the best way to do it,
but if you really want to use replace, you can also use
the replace method in loop:
suggested exercise: benchmark re.sub with literal replacement, re.sub
with callback (lambda m: ""), repeated replace, and repeated use of the form

if ch in my_string:
my_string = my_string.repla ce(ch, "")

on representative data.

</F>

Aug 13 '08 #5
Fredrik Lundh:
suggested exercise: benchmark re.sub with literal replacement, re.sub
with callback (lambda m: ""), repeated replace, and repeated use of the form
....
on representative data.
Please, add the translate() solution too I have suggested :-)

Bye,
bearophile
Aug 13 '08 #6
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.
--
John Krukoff <jk******@ltgc. com>
Land Title Guarantee Company

Aug 13 '08 #7
Dnia Wed, 13 Aug 2008 23:31:42 +0200, Fredrik Lundh napisa³(a):
>>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?

The regular expression is probably the best way to do it,
but if you really want to use replace, you can also use
the replace method in loop:

suggested exercise: benchmark re.sub with literal replacement, re.sub
with callback (lambda m: ""), repeated replace, and repeated use of the form

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. I mentioned above
that using re is the best approach, but if one really wants to use
replace() multiple times (which will be slow, of course), it can
be done a bit cleaner than with str.replace().r eplace().replac e()...

--
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
Aug 13 '08 #8
Wojtek Walczak wrote:
>suggested exercise: benchmark re.sub with literal replacement, re.sub
with callback (lambda m: ""), repeated replace, and repeated use of the form

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.

</F>

Aug 13 '08 #9
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.

:)
--
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
Aug 13 '08 #10

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

Similar topics

6
2254
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
2240
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
2888
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
854
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
2284
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
1919
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
1136
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
3391
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
8917
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
8761
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
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...
1
9200
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8148
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
6722
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
6022
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
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
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.