Strings are not numbers

>>> a='5'
>>> a+1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> a=5
>>> a+1

Notice that when the number is in quotes ‘5’ it’s not a number anymore (it’s called  a string).   When it doesn’t have quotes it’s treated as a number which can be added.

In fact, the issue isn’t that you can add numbers, but not strings, it’s that ‘5’  and 5 are different ‘types’.  ‘5’ is a string but 5 (no quotes) is an integer.  The two ‘types’ don’t mix. But you can still ‘add’ two strings together:

>>> a='5'
>>> a+'1'

Note here though that ‘1’ is not a number, it’s a string (because it has quotation marks around it).  Note also that it’s a sort of addition, but not as we’re used to it.   It’s called ‘concatenation’ which sort of means sticking together end to end.

Try it with some other strings:

>>> a = 'hello'
>>> b = 'there'
>>> a+b
>>> # hmmmm. maybe I need to add a space?
>>> a+' '+b
'hello there'

If you have a string, but want to have a number, Python has a way of trying to push it into a number, called int(). You put the string in the brackets and int will give you a number back if it can.  Sometimes it can’t.

>>> int('5')
>>> int('hi there')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hi there'

So, if you ever know you’ve got a number trapped inside a string, you can sometimes still get it out if you remember the int() function.

>>> a = '5'
>>> a+1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> int(a)+1
>>> a

See, in this example, that a is still a string, but we’ve managed to push its number out of it.

This is very important as you will often receive numbers hidden in strings and will need to convert them before you can do anything with  them.

3 Responses to Strings are not numbers

  1. sam says:

    thanks, this helps me alot
    >>> a = ‘death’
    >>> b = ‘star’
    >>> a+’ ‘+b
    ‘death star’
    here look at this

  2. Pingback: Consolidation: CryptoPyThy « Python Tutorials for Kids 8+

  3. John Doe says:

    How would I do this in Python 3?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: