-2

Ok so Im having a problem when printing something

Error:

TypeError: can only concatenate str (not "Element") to str

Code:

print(('Currently the weather in '+ query + 'is' + weath + 'with the temperature at ' + temp + 'degrees celsius'))
hyuhyuhyu
  • 1
  • 2
  • `Element` is a custom class, implement the `__str__` method – cards May 22 '22 at 18:51
  • Please include a [mcve]. What are `query`, `weath` and `temp`, and which one is causing the error? – TheFungusAmongUs May 22 '22 at 18:53
  • Welcome to Stack Overflow. There are two issues here. One is that, exactly as the error message tells you, strings can only be combined with other strings using `+`. One of those variables isn't a `str`, so a different approach is needed. The other problem is that the `Element` class might not look like anything you expect when printed. Please see the linked duplicates. – Karl Knechtel May 22 '22 at 19:04

1 Answers1

0

For a custom string representation of an instance

class A:
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return self.value


print('string ' + str(A('concatenation')))
#string concatenation

Without __str__

class B:
    def __init__(self, value):
        self.value = value

print('string ' + str(B('concatenation')))
#string <__main__.B object at 0x7f91f5dd5040>
cards
  • 3,936
  • 1
  • 7
  • 25