×

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages.

Ways to Append Strings in Python

We can append a string in two ways:

  1. Method 1: Using the += operator

There are some separate predefined functions in most of the programming languages to concatenate two strings like concat(). But in Python, we can use the += operator, making the task simpler and easier.

Syntax:

Result string = String1 + string2

Example program:

string1 = "Hello"
string2 = "!"
string3 = "world"
print ("The strings:")
print (string1)
print (string2)
print (string3)
result = string1 + string2 + “ ”+ string3
print ("The concatenated string is: ", result)

Output:

The strings:
Hello
!
world
The concatenated string is:  Hello! World

Explanation:

We have declared three strings and concatenated them along with a space to get the resultant sentence.

2. Method 2: Using the join () method

The main purpose of the join () method is to join all the elements in an iterable object ( list, tuple…) into a string with a separating character.

If we have more than 2 strings, it will be hard to keep adding one to the other by the above method. Join () method is feasible in such conditions. We can join any number of strings, and it is a predefined function in the Python libraries.

The unseen mechanism here is that the function creates a new list, and the strings are appended to the list. We use the join () method to merge these strings into one element that gives the final appended string.

Syntax:

“string”. join ([list of strings])
  • string: This is the string separating the strings to be concatenated.
  • List of strings: All the strings that need to be concatenated are converted into a single list/iterable.

Program:

string1 = "Hello"
string2 = "!"
string3 = "world"
print ("The strings:")
print (string1)
print (string2)
print (string3)
result = " ". join ([string1, string2, string3])
print ("The concatenated string is: ", result)

Output:

The strings:
Hello
!
world
The concatenated string is:  Hello! world

Explanation:

We gave the separating string as space. So, we got spaces between the words. Instead of adding strings using the + operator, we can call the join functions with all the strings as a list for multiple strings.

Method 3:

We can write several strings consecutively to concatenate them, but the drawback here is we can't perform this operation in string variables.

Example program:

result = 'ab''cd''e'
print ("The concatenated string is: ", result)

Output:

The concatenated string is abcde

Note: The spaces or backslash characters we give between the strings are not considered. The result will be the concatenated strings

Example:

Result = ‘a’       ‘b’     ‘c’
print (Result)

Output:

abc
  • Suppose we want to concatenate an integer or a floating-point number to a string. In that case, we need to convert the data type into the string using the str () function, and then we can go with concatenating because only strings can be concatenated.

Example programs:

string1 = "Hello"
string2 = 56
string3 = "world"
print ("The strings:")
print (string1)
print (string2)
print (string3)
result = string1 + str (string2) + string3
print ("The concatenated string is: ", result)

Output:

The strings:
Hello
56
world
The concatenated string is:  Hello56world

Explanation:

In the program, string2 is an integral value. We cannot concatenate an integer to a string. We used the str () function to convert it to a string and then used the concatenation.

There is another way to do this too. We can use the format () function. This function holds place and inserts a specified value into that space. Here is an example.

Program:

string1 = "Hello"
string2 = 56
string3 = "world"
print ("The strings:")
print (string1)
print (string2)
print (string3)
print ("The concatenated string is: {a}{b}{c}".format (a = string1,b = string2,c = string3))

Output:

The strings:
Hello
56
world
The concatenated string is: Hello56world

Explanation:

The integer value – string2 is not converted to a string in the program. Rather, in the print (), we used the format function and used 3 placeholders side by side and inserted string1, string2, and string3.

Using the list append () method

The append () method is defined only for lists. We need to convert the strings into lists when we want to use them.

Program:

string1 = "Hello"
string2 = "world"
print ("The strings:")
print (string1)
print (string2)
list1 = list (string1)
list2 = list (string2)
for i in list2:
    list1. append (i)
print ("The concatenated string is:","". join (list1))

Output:

The strings:
Hello
world
The concatenated string is: Helloworld

Explanation:

In above code, we iterated through list2, appended each character into list1, and converted it into a string using the join () function.

It is simply the inner mechanism of the join () method we used above.


Related Topics

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

IPython Display

A command shell, often known as IPython is a software application that makes an operating system's features accessible to users or other applications. Based on the purpose and specific functioning...

6 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.