string.replace doesn't removes ":"

Rick Johnson rantingrickjohnson at gmail.com
Tue Feb 12 23:44:09 EST 2013


On Saturday, February 9, 2013 5:04:18 AM UTC-6, Joshua Robinson wrote:
> Hi Monte-Pythons,
> 
> x = "this is a simple : text: that has colon"
> s = x.replace(string.punctuation, "");  OR
> s = x.replace(string.punctuation, ""); 
> print x   # 'this is a simple : text: that has colon'
> 
> # The colon is still in the text !!!!
> 
> Is this a bug or am I doing something wrong ?

Not a bug, you are just expecting Python to read your mind. In actuality what you are doing is asking the method "string.replace()" to replace the 32 char string:

   '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' 

with the null string: 

   ""

...what you INTENDED to do was have Python find every occurrence the each char in the string you passed and replace them with the null string. You are assuming the replace method handles sequences in the manner you are projecting. Sorry, but string#replace does not work that way. Whether or not it should is up for debate[1].

However, you can create a loop and pass the arguments "one-by-one" into the method:

py> s = "a:b  :c: d"
py> for char in string.punctuation:
	s = s.replace(char, "")	
py> s
'ab  c d'

But this seems really wasteful if all you want is to remove colons. Are you just removing the colons or truly wanting to remove ALL punctuation from the string?

============================================================
 REFERENCES:
============================================================

[1]: Should string.replace handle list, tuple and dict arguments in addition to strings?

py> string.replace(('a', 'b', 'c'), 'abcdefgabc')
'defg'
py> string.replace(['a', 'b', 'c'], 'abcdefgabc')
'defg'
py> string.replace({'a':'A', 'b':'2', 'c':'C'}, 'abcdefgabc')
'A2CdefgA2C'

This would be a more consistent approach to me. Handling only string arguments is woefully inadequate. Why would you have a programmer write a loop for this every time? 

@pydev&GvR
What is the justification for not processing (at the minimum) multiple arguments? Do you think strings will most often only need one modification?



More information about the Python-list mailing list