Force anything to be a string.
Tim Peters
tim_one at email.msn.com
Sat Sep 18 20:03:56 EDT 1999
[jonathon]
> I'm reworking a script, and keep running into this
> same basic sequence of errors.
>
> The offending lines are:
>
> string_check = check_list[50]
> string_check = str(string_check)
> string_check = string.capwords(string_check)
> check_list[50] = string_check
>
> This code snippet is supposed to take the object
> at check_list[50], convert it to a string, and
> then capitalize each word.
> #
> If fed a "normal" string of characters, it works.
> However, if check_list[50] is an integer, I either
> see the following error message:
>
> File "mass.py", line 20402 in align_everything(record_list)
> string_check = string.capwords(string_check)
> File "/usr/local/bin/python1.5/string.py" line 542 in capwords
> return join(map(capitalize, split(s, sep)), sep or' ')
> TypeError: arguement 1: expected read-only character buffer, int found
>
> or I see this error message:
>
> File "mass.py" , line 20402 in align_everything(record_list)
> string_check = str(string_check)
> TypeError: call of non-function ( type string )
>
> The difference is whether I have removed the line
> "string_check = str(string_check)"
> #
Makes sense so far.
> Question:
>
> 1: How can I ensure that string_check becomes a string,
> and not remain an integer? [ Other than error trapping at
> the source. An option not available, since this script reads
> files with bad data in them, to correct them. ]
Using the builtin str function was the correct approach from the start.
>From the error msgs you're getting, it looks most likely that you
accidentally rebound the name "str" to a string, so "str" no longer refers
to the builtin function (builtin function names are not reserved, which is
both a feature and a bug <0.7>).
This is how str normally works when applied to an integer:
>>> str(42)
'42'
>>>
Here's what happens if you bind "str" to a string by mistake:
>>> str = 'oops'
>>> str(42)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: call of non-function (type string)
>>>
The error msg there should look familiar. It's telling you that the syntax
looks like a call, but the object in the caller's position *can't* be called
("call of non-function"); and it's also giving the type of the object that
can't be called (str is of "type string").
diagnosis-may-be-easier-than-cure-ly y'rs - tim
More information about the Python-list
mailing list