[Tutor] str.replace error

Mats Wichmann mats at wichmann.us
Fri Apr 26 13:34:51 EDT 2019


On 4/25/19 10:29 PM, Steven D'Aprano wrote:
> On Thu, Apr 25, 2019 at 10:46:31AM -0700, Roger Lea Scherer wrote:
> 
>> with open('somefile') as csvDataFile:
>>     csvReader = csv.reader(csvDataFile)
>>     for row in range(100):
>>         a = "Basic P1"
>>         str.replace(a, "")
>>         print(next(csvReader))
> 
> 
> I'm not quite sure what you expected this to do, but you've 
> (deliberately? accidently?) run into one of the slightly advanced 
> corners of Python: unbound methods. 

accidentally, I believe.

notice that the way the Python 3 page on string methods is written, you
_could_ read it as you are to use the literal 'str' but in fact you are
expected to substitute in the name of your string object.

For this specific case:
===
str.replace(old, new[, count])

    Return a copy of the string with all occurrences of substring old
replaced by new. If the optional argument count is given, only the first
count occurrences are replaced.
===

So for the example above you're expected to do (without changing the
range call, which has been commented on elsewhere: you should just
iterate directly over the reader object, that's the way it's designed):

for row in range(100):
    a = "Basic P1"
    row.replace(a, "")

and then hopefully actually do something with the modified 'row', not
just go on to the next iteration and throw it away...



More information about the Tutor mailing list