473,545 Members | 2,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deleting specific characters from a string

Hi all,

I would like deleting specific characters from a string.
As an example, I would like to delete all of the '@' '&' in the string
'You are ben@orange?ente r&your&code' so that it becomes
'benorange?ente ryourcode'.

So far I have been doing it like:
str = 'You are ben@orange?ente r&your&code'
str = ''.join([ c for c in str if c not in ('@', '&')])

but that looks so ugly.. I am hoping to see nicer examples to acheive
the above..

Thanks.
Ben.

Jul 18 '05 #1
17 43422
Maybe a new method should be added to the str class, called "remove".
It would take a list of characters and remove them from the string:
class RemoveString(st r):
def __init__(self, s=None):
str.__init__(se lf, s)
def remove(self, chars):
s = self
for c in chars:
s = s.replace(c, '')
return(s)

if __name__ == '__main__':
r = RemoveString('a bc')
e = r.remove('c')
print r, e
# prints "abc ab" -- it's not "in place" removal

M@

Behrang Dadsetan <be*@dadsetan.c om> wrote in message news:<be******* ***@online.de>. ..
Hi all,

I would like deleting specific characters from a string.
As an example, I would like to delete all of the '@' '&' in the string
'You are ben@orange?ente r&your&code' so that it becomes
'benorange?ente ryourcode'.

So far I have been doing it like:
str = 'You are ben@orange?ente r&your&code'
str = ''.join([ c for c in str if c not in ('@', '&')])

but that looks so ugly.. I am hoping to see nicer examples to acheive
the above..

Thanks.
Ben.

Jul 18 '05 #2
In article <5a************ **************@ posting.google. com>,
Ma******@HeyAni ta.com (Matt Shomphe) wrote:
Maybe a new method should be added to the str class, called "remove".
It would take a list of characters and remove them from the string:


Check out the translate function - that's what its optional
deletions argument is for.

Donn Cave, do**@u.washingt on.edu
Jul 18 '05 #3
>>>>> "Matt" == Matt Shomphe <Ma******@HeyAn ita.com> writes:

Matt> Maybe a new method should be added to the str class, called
Matt> "remove". It would take a list of characters and remove
Matt> them from the string:

you can use string translate for this, which is shorter and faster
than using the loop.

class rstr(str):
_allchars = "".join([chr(x) for x in range(256)])
def remove(self, chars):
return self.translate( self._allchars, chars)

me = rstr('John Hunter')
print me.remove('ohn' )

Also, you don't need to define a separate __init__, since you are nor
overloading the str default.

JDH

Jul 18 '05 #4
Donn Cave wrote:
In article <5a************ **************@ posting.google. com>,
Ma******@HeyAni ta.com (Matt Shomphe) wrote:
Maybe a new method should be added to the str class, called "remove".
It would take a list of characters and remove them from the string:

Check out the translate function - that's what its optional
deletions argument is for.

str = 'You are Ben@orange?ente r&your&code'
str.translate(s tring.maketrans ('',''), '@&') and str.replace('&' , '').replace('@' , '')

are also ugly...

The first version is completely unreadable. I guess my initial example
''.join([ c for c in str if c not in ('@', '&')]) was easier to read
than the translate (who would guess -without having to peek in the
documentation of translate- that that line deletes @ and &?!) but I am
not sure ;)

while the second becomes acceptable. The examples you gave me use the
string module.
I think I read somewhere that the methods of the object should rather be
used than the string module. Is that right?

Thanks anyhow, I will go for the replace(somethi ng, '') method.
Ben.

Jul 18 '05 #5
Behrang Dadsetan wrote:
Hi all,

I would like deleting specific characters from a string.
As an example, I would like to delete all of the '@' '&' in the string
'You are ben@orange?ente r&your&code' so that it becomes
'benorange?ente ryourcode'.

So far I have been doing it like:
str = 'You are ben@orange?ente r&your&code'
str = ''.join([ c for c in str if c not in ('@', '&')])

but that looks so ugly.. I am hoping to see nicer examples to acheive
the above..


What about the following:

str = 'You are ben@orange?ente r&your&code'
str = filter(lambda c: c not in "@&", str)

Bye,
Walter Dörwald
Jul 18 '05 #6
Walter Dörwald wrote:
Behrang Dadsetan wrote:
Hi all,

I would like deleting specific characters from a string.
As an example, I would like to delete all of the '@' '&' in the
string 'You are ben@orange?ente r&your&code' so that it becomes
'benorange?ente ryourcode'.

So far I have been doing it like:
str = 'You are ben@orange?ente r&your&code'
str = ''.join([ c for c in str if c not in ('@', '&')])

but that looks so ugly.. I am hoping to see nicer examples to acheive
the above..

What about the following:

str = 'You are ben@orange?ente r&your&code'
str = filter(lambda c: c not in "@&", str)

Bye,
Walter Dörwald


def isAcceptableCha r(character):
return charachter in "@&"

str = filter(isAccept ableChar, str)

is going to finally be what I am going to use.
I not feel lambdas are so readable, unless one has serious experience in
using them and python in general. I feel it is acceptable to add a named
method that documents with its name what it is doing there.

But your example would probably have been my choice if I was more
familiar with that type of use and the potential readers of my code were
also familiar with it. Many thanks!

Ben.

Jul 18 '05 #7
Behrang Dadsetan wrote:
Walter Dörwald wrote:
Behrang Dadsetan wrote:
Hi all,

I would like deleting specific characters from a string.
As an example, I would like to delete all of the '@' '&' in the
string 'You are ben@orange?ente r&your&code' so that it becomes
'benorange?ente ryourcode'.

So far I have been doing it like:
str = 'You are ben@orange?ente r&your&code'
str = ''.join([ c for c in str if c not in ('@', '&')])

but that looks so ugly.. I am hoping to see nicer examples to acheive
the above..
What about the following:

str = 'You are ben@orange?ente r&your&code'
str = filter(lambda c: c not in "@&", str)

Bye,
Walter Dörwald

def isAcceptableCha r(character):
return charachter in "@&"

str = filter(isAccept ableChar, str)

is going to finally be what I am going to use.
I not feel lambdas are so readable, unless one has serious experience in
using them and python in general. I feel it is acceptable to add a named
method that documents with its name what it is doing there.


You're not the only one with this feeling. Compare "the eff-bot's
favourite lambda refactoring rule":

http://groups.google.de/groups?selm=...ewsb.telia.net
[...]


Bye,
Walter Dörwald

Jul 18 '05 #8
>>>>> "Behrang" == Behrang Dadsetan <be*@dadsetan.c om> writes:

Behrang> is going to finally be what I am going to use. I not
Behrang> feel lambdas are so readable, unless one has serious
Behrang> experience in using them and python in general. I feel it
Behrang> is acceptable to add a named method that documents with
Behrang> its name what it is doing there.

If you want to go the functional programing route, you can generalize
your function somewhat using a callable class:

class remove_char:
def __init__(self,r emove):
self.remove = dict([ (c,1) for c in remove])

def __call__(self,c ):
return not self.remove.has _key(c)

print filter(remove_c har('on'), 'John Hunter')

Cheers,
Jh Huter

Jul 18 '05 #9
On Wed, 09 Jul 2003 23:36:03 +0200, Behrang Dadsetan <be*@dadsetan.c om> wrote:
Walter Dörwald wrote:
Behrang Dadsetan wrote:
Hi all,

I would like deleting specific characters from a string.
As an example, I would like to delete all of the '@' '&' in the
string 'You are ben@orange?ente r&your&code' so that it becomes
'benorange?ente ryourcode'.

So far I have been doing it like:
str = 'You are ben@orange?ente r&your&code'
str = ''.join([ c for c in str if c not in ('@', '&')])

but that looks so ugly.. I am hoping to see nicer examples to acheive
the above..

What about the following:

str = 'You are ben@orange?ente r&your&code'
str = filter(lambda c: c not in "@&", str) Aaack! I cringe seeing builtin str name rebound like that ;-/

Bye,
Walter Dörwald


def isAcceptableCha r(character):
return charachter in "@&"

return character not in "@&"
str = filter(isAccept ableChar, str)

is going to finally be what I am going to use. That's not going to be anywhere near as fast as Donn's translate version.
I not feel lambdas are so readable, unless one has serious experience in
using them and python in general. I feel it is acceptable to add a named
method that documents with its name what it is doing there.

But your example would probably have been my choice if I was more
familiar with that type of use and the potential readers of my code were
also familiar with it. Many thanks!
IMO, if you are going to define a function like isAcceptableCha r, only to use it
with filter, why not write a function to do the whole job, and whose invocation
reads well, while hiding Donn's fast translate version? E.g., substituting the literal
value of string.maketran s('',''):

====< removechars.py >============== =============== =============== ============
def removeChars(s, remove=''):
return s.translate(
'\x00\x01\x02\x 03\x04\x05\x06\ x07\x08\t\n\x0b \x0c\r\x0e\x0f'
'\x10\x11\x12\x 13\x14\x15\x16\ x17\x18\x19\x1a \x1b\x1c\x1d\x1 e\x1f'
' !"#$%&\'()*+ ,-./'
'0123456789:;<= >?'
'@ABCDEFGHIJKLM NO'
'PQRSTUVWXYZ[\\]^_'
'`abcdefghijklm no'
'pqrstuvwxyz{|} ~\x7f'
'\x80\x81\x82\x 83\x84\x85\x86\ x87\x88\x89\x8a \x8b\x8c\x8d\x8 e\x8f'
'\x90\x91\x92\x 93\x94\x95\x96\ x97\x98\x99\x9a \x9b\x9c\x9d\x9 e\x9f'
'\xa0\xa1\xa2\x a3\xa4\xa5\xa6\ xa7\xa8\xa9\xaa \xab\xac\xad\xa e\xaf'
'\xb0\xb1\xb2\x b3\xb4\xb5\xb6\ xb7\xb8\xb9\xba \xbb\xbc\xbd\xb e\xbf'
'\xc0\xc1\xc2\x c3\xc4\xc5\xc6\ xc7\xc8\xc9\xca \xcb\xcc\xcd\xc e\xcf'
'\xd0\xd1\xd2\x d3\xd4\xd5\xd6\ xd7\xd8\xd9\xda \xdb\xdc\xdd\xd e\xdf'
'\xe0\xe1\xe2\x e3\xe4\xe5\xe6\ xe7\xe8\xe9\xea \xeb\xec\xed\xe e\xef'
'\xf0\xf1\xf2\x f3\xf4\xf5\xf6\ xf7\xf8\xf9\xfa \xfb\xfc\xfd\xf e\xff'
, remove)

if __name__ == '__main__':
import sys
args = sys.argv[1:]
fin = sys.stdin; fout=sys.stdout ; remove='' # defaults
while args:
arg = args.pop(0)
if arg == '-fi': fin = file(args.pop(0 ))
elif arg == '-fo': fout = file(args.pop(0 ))
else: remove = arg
for line in fin:
fout.write(remo veChars(line, remove))
=============== =============== =============== =============== =============== ===
Not tested beyond what you see here ;-)

[16:40] C:\pywk\ut>echo "'You are ben@orange?ente r&your&code'" |python removechars.py "@&"
"'You are benorange?enter yourcode'"

[16:41] C:\pywk\ut>echo "'You are ben@orange?ente r&your&code'" |python removechars.py aeiou
"'Y r bn@rng?ntr&yr&c d'"

Copying a snip above to the clipboard and filtering that with no removes and then (lower case) vowels:

[16:41] C:\pywk\ut>getc lip |python removechars.pyI not feel lambdas are so readable, unless one has serious experience in
using them and python in general. I feel it is acceptable to add a named
method that documents with its name what it is doing there.

But your example would probably have been my choice if I was more
familiar with that type of use and the potential readers of my code were
also familiar with it. Many thanks!
[16:42] C:\pywk\ut>getc lip |python removechars.py aeiouI nt fl lmbds r s rdbl, nlss n hs srs xprnc n
sng thm nd pythn n gnrl. I fl t s ccptbl t dd nmd
mthd tht dcmnts wth ts nm wht t s dng thr.

Bt yr xmpl wld prbbly hv bn my chc f I ws mr
fmlr wth tht typ f s nd th ptntl rdrs f my cd wr
ls fmlr wth t. Mny thnks!

Regards,
Bengt Richter
Jul 18 '05 #10

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

Similar topics

3
1401
by: Thaynann | last post by:
is there a way to delete a block of text i have started by looking for the speicific line of text that starts the block by looking for teh index of it...but i cannot figure out out to remove that text from the file..can anyone help me?
2
2151
by: Branden | last post by:
hi guys, i was wondering if it is possible to extract selected words in a field to be put in different fields automatically. Do i have to write the code in vb? This is what im trying to do. Write now, i have emails that i receive in outlook and i want to transfer them into a database. I realized that i could export this. however, the BODY...
3
3325
by: Zheve | last post by:
Help please, I want to write a query to delete spaces and other various between numbers (which is set as text field due to the data that is put in) as follows: Currently as: 0-9-123 4567 OR 0-9-765-4321 Result I want:
0
350
by: Maxxam | last post by:
Hi, I have a simple question but i can't solve it simple. How can i remove carriage returns and linfeed characters , \n\r, form a string? Thanks, Andre
2
6844
by: melanieab | last post by:
Hi, I'm trying to store all of my data into one file (there're about 140 things to keep track of). I have no problem reading a specific string from the array file, but I wasn't sure how to replace just one item. I know I can get the entire array, then save the whole thing (with a for loop and if statements so that the changed data will be...
5
2768
by: FefeOxy | last post by:
Hi, > I'm having a debug assertion error within the file dbgdel.cpp with the expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) I traced the origin of the error and it happened as I tried to delete a polymorphic class as follows:
1
2747
by: arv6004u | last post by:
Hi, I have created Map Data stacture. Each map Entry contains hostname and it's value. I have traversed the map using iterator then i want to delete specific hostname entry and to change the remaining map value for the existing hostnames. My sample code as follows. typedef struct _CAAMT_Credentials {
2
1470
by: Mike P2 | last post by:
I made a Stream-inheriting class that just removes the tabs (actually the 4 spaces VS prefers to use) from the beginning of lines and empty lines. At first I was having trouble with it adding a null character in the middle of the output. I think it was a null character, Firefox displays it as a '?' and the W3C validator says it's a non-sgml...
3
4341
by: evenlater | last post by:
I have an Access application on a terminal server. Sometimes my users need to export reports to pdf, rtf or xls files and save them to their own client device hard drives. They can do that right now the way I have this set up, but it's confusing and slow. When they browse for a place to save the reports, they see all of the drives on the...
0
7499
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...
0
7432
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...
0
7689
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. ...
1
7456
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...
0
6022
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...
0
3490
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...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1044
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
743
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...

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.