[Tutor] wordcount.py query

Steven D'Aprano steve at pearwood.info
Thu Jun 28 04:37:15 CEST 2012

On Thu, Jun 28, 2012 at 12:59:45AM +0100, Imran Javeed wrote:

> Im trying to replay the code on the python cmd line but keep getting this
> error
> >>> w_count[string] = w_count[string] + 1
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: cannot concatenate 'str' and 'int' objects
> I was trying to recreate the scenario whereby the dict value is incremented
> by 1 as in the following code, it works in the python script but not when i
> manually create & populate the dict value & increment it on the pythin cmd
> line, can you please explain why?

Is the error message not clear? If you have a suggestion for what would 
be more helpful to you, please tell us.

You are trying to concatenate (join) a string and an int (a number), and 
Python will not let you do that. Both these examples will raise an 

"hello world" + 1
"42" + 1

These however will succeed:

"hello world" + "1"
"42" + "1"
42 + 1

Python is not Perl -- if you pass a string and a number to the plus 
operator, Python will not try to guess whether you wanted addition or 
concatenation. You must use two strings, or two numbers.

If still having trouble diagnosing the problem, you can do this at the 
interactive interpreter:


That will show you the values causing trouble.


More information about the Tutor mailing list