Friday, May 3, 2024
HomePythonTypeError: can solely concatenate str (not "int") to str

TypeError: can solely concatenate str (not “int”) to str


Trey Hunner smiling in a t-shirt against a yellow wall

Trey Hunner


5 minute learn



Python 3.7—3.10

Your Python program crashed and displayed a traceback like this one:

Traceback (most up-to-date name final):
  File "copyright.py", line 4, in <module>
    assertion = "Copyright " + yr
TypeError: can solely concatenate str (not "int") to str

Or possibly you noticed a variation on that message:

Traceback (most up-to-date name final):
  File "names.py", line 3, in <module>
    print("Hey" + names)
TypeError: can solely concatenate str (not "checklist") to str

Or you’ll have seen a special error message that mentions + and int and str:

Traceback (most up-to-date name final):
  File "add.py", line 5, in <module>
    print(begin + quantity)
TypeError: unsupported operand kind(s) for +: 'int' and 'str'

What do these imply?
And how will you repair your code?

What does that error message imply?

The final line is in a Python traceback message is crucial one.

TypeError: can solely concatenate str (not "int") to str

That final line says the exception kind (TypeError) and the error message (can solely concatenate str (not "int") to str).

This error message says one thing comparable:

TypeError: unsupported operand kind(s) for +: 'int' and 'str'

Each of those error messages are attempting to inform us that we’re making an attempt to make use of the + operator (used for string concatenation in Python) between a string and a quantity.

You should utilize + between a string and a string (to concatenate them) or a quantity and a quantity (so as to add them).
However in Python, you can not use + between a string and a quantity as a result of Python would not do automated kind coercion.
Sort conversions are normally finished manually in Python.

How will we repair this?

How we repair this can rely upon our wants.

Have a look at the code the error occurred on (keep in mind that tracebacks are learn from the bottom-up in Python).

  File "copyright.py", line 4, in <module>
    assertion = "Copyright " + yr

Ask your self “what am I making an attempt to do right here?”
You are probably both making an attempt to:

  1. Construct an even bigger string (through concatenation)
  2. Add two numbers collectively
  3. Use + in one other manner (e.g. to concatenate lists)

As soon as you’ve got discovered what you are making an attempt to do, then you definitely’ll then want to determine the way to repair your code to perform your aim.

Changing numbers to strings to concatenate them

If the problematic code is supposed to concatenate two strings, we’ll have to explicitly convert our non-string object to a string.
For numbers and plenty of different objects, that is so simple as utilizing the built-in str perform.

We might exchange this:

assertion = "Copyright " + yr

With this:

assertion = "Copyright " + str(yr)

Although in lots of circumstances it could be extra readable to make use of string interpolation (through f-strings):

assertion = f"Copyright {yr}"

This works as a result of Python robotically calls the str perform on all objects inside the alternative fields in an f-string.

Changing different objects to strings

Utilizing the str perform (or an f-string) will work for changing a quantity to a string, nevertheless it will not at all times produce good output for different objects.

For instance when making an attempt to concatenate a string and an inventory:

>>> names = ["Judith", "Andrea", "Verena"]
>>> user_message = "Customers embrace: " + names
Traceback (most up-to-date name final):
  File "<stdin>", line 1, in <module>
TypeError: can solely concatenate str (not "checklist") to str

You may assume to make use of str to transform the checklist to a string:

>>> user_message = "Customers embrace: " + str(names)

This does work, however the ensuing string may not look fairly the best way you’d anticipate:

>>> print(user_message)
Customers embrace: ['Judith', 'Andrea', 'Verena']

When changing an inventory to a string you may probably wish to be a part of collectively the checklist objects utilizing the string be a part of methodology.

>>> user_message = "Customers embrace: " + ", ".be a part of(names)
>>> print(user_message)
Customers embrace: Judith, Andrea, Verena

Different forms of objects could require a special strategy: the string conversion approach you utilize will rely upon the thing you are working with and the way you’d prefer it to look inside your string.

Changing strings to numbers so as to add them

What if our code is not imagined to concatenate strings?
What if it is meant to add numbers collectively?

If we’re seeing one in all these two error messages whereas making an attempt so as to add numbers collectively:

  • TypeError: can solely concatenate (not "int") to str
  • TypeError: unsupported operand kind(s) for +: 'int' and 'str'

Which means one in all our “numbers” is presently a string!

This usually occurs when accepting a command-line argument that ought to characterize a quantity:

$ python saving.py 100
Traceback (most up-to-date name final):
  File "saving.py", line 7, in <module>
    whole += sys.argv[1]
TypeError: unsupported operand kind(s) for +=: 'int' and 'str'

Command-line arguments are sometimes a difficulty as a result of all command-line arguments come into Python as strings.
So the sys.argv checklist in that saving.py program may appear to be this:

>>> sys.argv
['saving.py', '100']

Word: If command-line arguments are the difficulty, you could wish to look into utilizing argparse to parse your command-line arguments into the right sorts.

This numbers-represented-as-strings subject may also happen when prompting the consumer with the built-in enter perform.

>>> whole = 0
>>> user_input = enter("Additionally add: ")
Additionally add: 100
>>> whole += user_input
Traceback (most up-to-date name final):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand kind(s) for +=: 'int' and 'str'

The enter perform shops every thing the consumer entered right into a string:

No matter the way it occurred, if you wish to convert your string which represents a quantity to an precise quantity, you need to use both the built-in float perform or the built-in int perform:

>>> user_input
'100'
>>> deposit = float(user_input)
>>> deposit
100.0
>>> deposit = int(user_input)
>>> deposit
100

The float perform will settle for numbers with a decimal level.
The int perform will solely settle for integers (numbers with no decimal level).

Bear in mind: kind conversions normally have to be express

That can solely concatenate str (not "int") to str error message reveals up ceaselessly in Python as a result of Python doesn’t have kind coercion.

Every time you may have a string and a non-string and also you’d wish to both sum them with + or concatenate them with +, you may have to explicitly convert your object to a special kind.

All knowledge that comes from exterior of your Python course of begins as binary knowledge (bytes) and Python sometimes converts that knowledge to strings.
Whether or not you are studying command-line arguments, studying from a file, or prompting a consumer for enter, you may probably find yourself with strings.

In case your knowledge represents one thing deeper than a string, you may have to convert these strings to numbers (or no matter kind you want):

>>> c = a + int(b)
>>> a, b, c
(3, '4', 7)

Likewise, if in case you have non-strings (whether or not numbers, lists, or just about another object) and also you’d wish to concatenate these objects with strings, you may have to convert these non-strings to strings:

>>> yr = 3000
>>> message = "Welcome to the yr " + str(yr) + "!"
>>> print(message)
Welcome to the yr 3000!

Although keep in mind that f-strings is likely to be a greater possibility than concatenation:

>>> yr = 3000
>>> message = f"Welcome to the yr {yr}!"
>>> print(message)
Welcome to the yr 3000!

And keep in mind that pleasant string conversions generally require a bit greater than a str name (e.g. changing lists to strings).

Ideas Past Intro to Python

Intro to Python programs usually skip over some elementary Python ideas.

Enroll beneath and I am going to share concepts new Pythonistas usually overlook.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments