string.replace() produces TypeError: an integer is required

John Machin sjmachin at lexicon.net
Wed Mar 12 16:05:45 EST 2003


Max M <maxm at mxm.dk> wrote in message news:<3E6EEE3C.20105 at mxm.dk>...
> theKid wrote:
> > As far as I can tell, I'm using the function correctly:
> >                 import string
> >                 import types
> >                 print type(data)
> >                 print data
> > 		data = string.replace(data, '\t', '\\t')             # line 58
> > 		data = string.replace(data, '\n', '\\n')
> > 		print data
> > Am I using string.replace() correctly?
> 
> 
> Yes. Most likely the problem is that you have deleted your "data" 
> variable by mistake. It works when I define data.
> 

Bzzzzt. Most *UN*likely. Look at the subject: "TypeError: an integer
is required" -- that's not caused by having unbound the first
argument.

Furthermore, the code posted by the OP can not have caused "TypeError:
an integer is required.", even if "data" was bound to something. The
OP should make up the shortest possible .py file that causes this
exception, and post it, together with the traceback that occurs when
it is run.

In the meantime, both the OP and Max may gain some enlightenment by
perusing the following:

>>> import string
>>> data = "yaddayadda"
>>> string.replace(data, "a", "o")
'yoddoyoddo'
>>> del data
>>> string.replace(data, "a", "o")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'data' is not defined
>>> data = "yaddayadda"
>>> string.replace(data, "a", "o", 2)
'yoddoyadda'
>>> string.replace(data, "a", "o", "not an int")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "c:\python22\lib\string.py", line 370, in replace
    return s.replace(old, new, maxsplit)
TypeError: an integer is required
>>>

Oh and why are you not using data.replace(...) instead of
string.replace(data, ...)??? As you can see from the above traceback,
the second calls the first -- a tad wasteful.

HTH,
John




More information about the Python-list mailing list