Python string concatenation with examples

Python string concatenation with examples

String concatenation in Python

In Python, strings can be concatenated by using the + operator. Following are a few examples of string concatenation.

An example of Concatenation

The following example simply joins two sentences and displays it.

Python concatenation

See this example online

String concatenation of two variables

In the following example of Python string concatenation, we will use two string variables and combine those by using the ‘+’ operator. See the code with output!

See this example online

The output will be:

This is Python Tutorial. This is concatenation chapter

What happens if an int is concatenated?

If an Int is tried to concatenate with string then an error will be generated.

See this example online

This will be output with an error message:

Traceback (most recent call last):

File “C:\PythonPrograms\shell.py”, line 4, in <module>

print (str1 + ” ” + int1)

TypeError: Can’t convert ‘int’ object to str implicitly

You have to convert an int to the string by using the str() method in order to concatenate this. See example below:

See this example online

The output will be:

This is Python Tutorial. 123

 

Further reading: String length | Python Tuple