×

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

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute 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.

Python and its advantages

What is Python? Python is an object-oriented programming language, a general-purpose programming language with a high level, and also an interpreted language that has an easy syntax and dynamic semantics. Python...

7 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Add Element to Tuple in Python

Python: Popular high-level, all-purpose programming language Python. The new version of the Python programming language, Python 3, is used for all software applications, including web development. Python is the best programming...

4 minutes read.

Find key from value in dictionary python

Python: Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a...

5 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.