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

Peter Hansen peter at engcorp.com
Thu Mar 13 10:18:24 EST 2003


John Machin wrote:
> 
> 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

By Jove, I think you've found it!

Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
>>> import string
>>> data = "hi\tthere"
>>> print type(data)
<type 'string'>
>>> print data
hi      there
>>> data = string.replace(data, '\t', '\\t')
>>> data
'hi\\tthere'
>>> string = data
>>> data = string.replace(data, '\t', '\\t')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: an integer is required


Conclusion: the OP has at some point rebound the name "string" at 
to an actual string...

-Peter




More information about the Python-list mailing list