I have written some code to count the number of upper case letters in a string and the last line will not work?

I am trying to print a statement that concatenates a line of text and an integer variable:

print ("The number of upper case letters are: " + upper)

When I run the code it give me the following error:

Traceback (most recent call last):
File "C:\Users\Emma\Desktop\Test", line 36, in <module>
print ("The number of upper case letters are: " + upper)
TypeError: Can't convert 'int' object to str implicitly

Any help would be gratefully received.

Recommended Answers

All 2 Replies

Member Avatar for Enalicho

upper is a integer - what your error is telling you is that you can't add strings and integers together.

You could do [1]

print ("The number of upper case letters are: " + str(upper))

Or better yet, use old style string formatting. %d is a specifier for integers, so I would do [2] -

print ("The number of upper case letters are: %d" % upper)

Or [3] -

print ("The number of upper case letters are: {}".format(upper))

Or if you're using Python3.x [4],

print ("The number of upper case letters are: ", upper)

[1] - http://docs.python.org/library/functions.html#str
[2] - http://docs.python.org/library/stdtypes.html#string-formatting-operations
[3] - http://docs.python.org/library/string.html#format-specification-mini-language
[4] - http://docs.python.org/release/3.2.1/library/functions.html#print

Note, if you aren't using Python 3.x, you don't need the brackets.

commented: Thorough +13

Thats really useful thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.