How to concatenate two strings in Python

In this tutorial, we will learn how to concatenate two strings in Python. There are different ways of string concatenation. Let’s explore one by one.

Strings are a collection of characters inside single quotes or double-quotes. Strings have immutability property, i.e. we cannot mutate the string but the value of a variable can be changed to a new string.

You may learn: how to escape quotes in Python

Concatenation of two string in Python

Two or more strings can be combined and the process is known as string concatenation. Take two strings, merge them and they will become one.
For example, let the first string be “Code” and the other be “Speedy“. After concatenation, they will become “Code Speedy“.

There are several ways by which we can concatenate strings in Python.

  1. Using ‘+’ operator: Concatenate strings in Python

    "First String"+"Second string"
    'First stringSecond String'
  2. If we want to add space between the strings, then write your code as follows:

    Add space in between two strings while concatenating two strings in Python

    "Welcome to " + "Codespeedy"
    'Welcome to Codespeedy'
  3. Another method for giving space:
    "Welcome to" + ' ' + "Codespeedy"
    'Welcome to Codespeedy'

    Or the strings can be assigned to variables and then concatenated:

    a = "Welcome to"
    b = "Codespeedy"
    c = ' '
    d = a+c+b
    'Welcome to Codespeedy'
  4. We cannot add an integer to a string.

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

    a = "Hello"
    Traceback (most recent call last):
    File "<pyshell#5>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str

    We need to convert the integer to string using str().

  5. To print a single string multiple times:

Leave a Reply

Your email address will not be published. Required fields are marked *