0

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.

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by CaptainHook
1

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.

Edited by Enalicho: n/a

Votes + Comments
Thorough
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.