How do you concatenate objects and strings in python?

How to concatenate Object with a string (primitive) without overloading and explicit type cast (str())?

class Foo:
    def __init__(self, text):
        self.text = text

    def __str__(self):
        return self.text


_string = Foo('text') + 'string'

Output:

Traceback (most recent call last):
  File "test.py", line 10, in 
      _string = Foo('text') + 'string'

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

operator + must be overloaded? Is there other ways (just wondering)?

PS: I know about overloading operators and type casting (like str(Foo('text')))

asked Feb 16, 2012 at 16:03

tomastomas

4412 gold badges5 silver badges13 bronze badges

6

Just define the __add__() and __radd__() methods:

class Foo:
    def __init__(self, text):
        self.text = text
    def __str__(self):
        return self.text
    def __add__(self, other):
        return str(self) + other
    def __radd__(self, other):
        return other + str(self)

They will be called depending on whether you do Foo("b") + "a" (calls __add__()) or "a" + Foo("b") (calls __radd__()).

answered Feb 16, 2012 at 16:08

Sven MarnachSven Marnach

544k114 gold badges914 silver badges816 bronze badges

5

_string = Foo('text') + 'string'

The problem with this line is that Python thinks you want to add a string to an object of type Foo, not the other way around.

It would work though if you'd write:

_string = "%s%s" % (Foo('text'), 'string')

EDIT

You could try it with

_string = 'string' + Foo('text')

In this case your Foo object should be automatically casted to a string.

answered Feb 16, 2012 at 16:06

ConstantiniusConstantinius

33.1k7 gold badges74 silver badges84 bronze badges

4

If that makes sense for your Foo object, you can overload the __add__ method as follows:

class Foo:
    def __init__(self, text):
        self.text = text

    def __str__(self):
        return self.text

    def __add__(self, other):
        return str(self) + other

_string = Foo('text') + 'string'
print _string

Example output:

textstring

answered Feb 16, 2012 at 16:08

jcolladojcollado

38.2k8 gold badges101 silver badges133 bronze badges

String Concatenation is a very common operation in programming. Python String Concatenation can be done using various ways. This tutorial is aimed to explore different ways to concatenate strings in a python program.

Python String Concatenation

We can perform string concatenation using following ways:

  • Using + operator
  • Using join() method
  • Using % operator
  • Using format() function
  • Using f-string (Literal String Interpolation)

String Concatenation using + Operator

This is the most simple way of string concatenation. Let’s look at a simple example.

s1 = 'Apple'
s2 = 'Pie'
s3 = 'Sauce'

s4 = s1 + s2 + s3

print(s4)

Output: ApplePieSauce Let’s look at another example where we will get two strings from user input and concatenate them.

s1 = input('Please enter the first string:\n')
s2 = input('Please enter the second string:\n')

print('Concatenated String =', s1 + s2)

Output:

Please enter the first string:
Hello
Please enter the second string:
World
Concatenated String = HelloWorld

How do you concatenate objects and strings in python?
It’s very easy to use + operator for string concatenation. However, the arguments must be a string.

>>>'Hello' + 4
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "int") to str

We can use str() function to get the string representation of an object. Let’s see how to concatenate a string to integer or another object.

print('Hello' + str(4))


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[' + str(self.id) + ']'


print('Hello ' + str(Data(10)))

Output:

Hello4
Hello Data[10]

The biggest issue with + operator is that we can’t add any separator or delimiter between strings. For example, if we have to concatenate “Hello” and “World” with a whitespace separator, we will have to write it as "Hello" + " " + "World".

String concatenation using join() function

We can use join() function to concatenate string with a separator. It’s useful when we have a sequence of strings, for example list or tuple of strings. If you don’t want a separator, then use join() function with an empty string.

s1 = 'Hello'
s2 = 'World'

print('Concatenated String using join() =', "".join([s1, s2]))

print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))

Output:

Concatenated String using join() = HelloWorld
Concatenated String using join() and spaces = Hello World

String Concatenation using % Operator

We can use % operator for string formatting, it can be used for string concatenation too. It’s useful when we want to concatenate strings and perform simple formatting.

s1 = 'Hello'
s2 = 'World'

s3 = "%s %s" % (s1, s2)
print('String Concatenation using % Operator =', s3)

s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018)
print('String Concatenation using % Operator with Formatting =', s3)

Output:

String Concatenation using % Operator = Hello World
String Concatenation using % Operator with Formatting = Hello World from JournalDev - 2018

String Concatenation using format() function

We can use string format() function for string concatenation and formatting too.

s1 = 'Hello'
s2 = 'World'

s3 = "{}-{}".format(s1, s2)
print('String Concatenation using format() =', s3)

s3 = "{in1} {in2}".format(in1=s1, in2=s2)
print('String Concatenation using format() =', s3)

Output:

String Concatenation using format() = Hello-World
String Concatenation using format() = Hello World

Python String format() function is very powerful, using it just for concatenation of strings is not its proper use.

String Concatenation using f-string

If you are using Python 3.6+, you can use f-string for string concatenation too. It’s a new way to format strings and introduced in PEP 498 - Literal String Interpolation.

s1 = 'Hello'
s2 = 'World'

s3 = f'{s1} {s2}'
print('String Concatenation using f-string =', s3)

name = 'Pankaj'
age = 34
d = Data(10)

print(f'{name} age is {age} and d={d}')

Output:

String Concatenation using f-string = Hello World
Pankaj age is 34 and d=Data[10]

Python f-string is cleaner and easier to write when compared to format() function. It also calls str() function when an object argument is used as field replacement.

Conclusion

Python String formatting can be done in several ways. Use them based on your requirements. If you have to concatenate sequence of strings with a delimited, then use join() function. If some formatting is also required with concatenation, then use format() function or f-string. Note that f-string can be used with Python 3.6 or above versions.

You can checkout complete python script and more Python examples from our GitHub Repository.

Can you concatenate strings and variables in Python?

There are various ways by which you can concatenate multiple strings in Python. The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator.

How do you concatenate strings and numbers in Python?

Python supports string concatenation using the + operator. In most other programming languages, if we concatenate a string with an integer (or any other primitive data types), the language takes care of converting them to a string and then concatenates it.

What is the best way to concatenate strings in Python?

One of the most popular methods to concatenate two strings in Python (or more) is using the + operator. The + operator, when used with two strings, concatenates the strings together to form one.

Can you concatenate strings and floats in Python?

In Python, We cannot use the + operator to concatenate one string and float type. We cannot concatenate a string with a non-string type. We will use str() to convert the float to string type and then it will be concatenated.