Python

Python String Append Example

In this article, we will explain the string append in Python.

1. Introduction

In Python, the string is an immutable object. You can use the ‘+’ operator to append two strings to create a new string. There are various ways such as using join, format, string IO, and appending the strings with space.

2. Python String Append

In this section, we will look at multiple ways of appending strings using python API.

2.1 + operator

‘+’ Operator joins two strings. The code below shows appending of two strings with space in between.

+ Operator

str1 = "Hello"
str2 = "World"
space = " "
print(str1 + space + str2)

The command below tries to execute the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - + operator
+ operator

2.2 * operator

‘*’ Operator joins the string with int. The code snippet for using the ‘*’ operator is shown below.

* Operator

print('black' * 5)

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - * operator
* operator

2.3 string appending to int

A string cannot be appended directly with int as shown in the snippet below.

string appending to int

print('green' + 8)

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below. An exception occurs showing that string and int cannot be appended

Python String Append - Exception : str +int
Exception : str +int

The right way is to use the str method to convert int to a string. The code snippet using the str method is shown below.

string appending to int

print('green' + str(8))

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - int to string
int to string

2.4 % operator

‘%’ operator is used to append strings within a string using format syntax. The code snippet for using the ‘%’ operator is shown below.

% operator

fruit1 = 'grapes'
fruit2 = 'apples'
fruit3 = "The basket has these fruits: %s and %s" % (fruit1,fruit2)

print(fruit3)

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - % operator
% operator

2.5 format method

Format operator is used for appending strings within a string as shown in the code snippet below.

format operator

Firstname = "Pierce"
Lastname = "Brosnan"
Age = "54"
Str = "{} {}'s Age is {} ".format(Firstname, Lastname, Age)
print(Str)

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - format method
format method

2.6 Join method

Another way to append strings is by creating a list and adding strings to the list. The join method merges the strings together to get the result. The code snippet using the join method is shown below.

Join method

string = ' ' .join(['the', 'cat', 'jumps', 'over', 'the', 'wall'])

print(string)

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - join method
Join method

Another example showing the join method appending strings in an array is presented below.

Join method

music_album = ["Stone Cold","Metallica", "Rolling Stones", "One Dance","Perfect Strangers"]
print("".join(music_album))

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - Join array
Join array

2.7 Concatenate with Space

The other way of appending the strings is to join a list of strings by including empty space. Concatenating with space is shown in the code snippet below.

Concatenate with space

print ('Concatenate '  'With ' 'Space')

The command below executes the above code snippet.

Run Command

 python python_string_append.py

The output of the executed command is shown below.

Python String Append - concatenate with space
concatenate with space

2.8 String io method

String IO is an in-memory stream for text input and output processing. The API is used to append strings. The code snippet shown below presents the string io usage.

String io

from io import StringIO
 
 
 
concat_str = StringIO()
 
 
 
concat_str.write('This ')
 
concat_str.write('example ')
 
concat_str.write('is ')
 
concat_str.write('for ')

concat_str.write('StringIO')
 
print(concat_str.getvalue())

The command below executes the above code snippet.

Run Command

 python concat_string.py

The output of the executed command is shown below.

Python String Append - string io
String IO

2.9 Reading a log file

The code sample below shows reading lines from a log file and appending the string lines.

Reading a log file

with open('log.txt') as file:
    log_file = file.readlines()

new_log_lines = ''
for line in log_file:
    if line[:6] == 'ERROR:':
        new_log_lines = new_log_lines + line
        
print(new_log_lines) 

The log file text is shown below.

log.txt

111.222.333.123 HOME - [01/Feb/1998:01:08:39 -0800] "GET /bannerad/ad.htm HTTP/1.0" 200 198 "http://www.mozmac.com/ba_intro.htm" "Mozilla/4.01 (Macintosh; I; PPC)"
ERROR: link not working
111.222.333.123 HOME - [01/Feb/1998:01:08:46 -0800] "GET /bannerad/ad.htm HTTP/1.0" 200 28083 "http://www.mozmac.com/ba_intro.htm" "Mozilla/4.01 (Macintosh; I; PPC)"
111.222.333.123 AWAY - [01/Feb/1998:01:08:53 -0800] "GET /bannerad/ad7.gif HTTP/1.0" 200 9332 "http://www.mozmac.com/ba_ad.htm" "Mozilla/4.01 (Macintosh; I; PPC)"
ERROR: link not working
111.222.333.123 AWAY - [01/Feb/1998:01:09:14 -0800] "GET /bannerad/click.htm HTTP/1.0" 200 207 "http://www.mozmac.com/menu.htm" "Mozilla/4.01 (Macintosh; I; PPC)"

The command below executes the above code snippet.

Run Command

 python python_line_append.py

The output of the executed command is shown below.

Python String Append - line appending
line appending

You can find more Python tutorials here.

3. Download the Source Code

Download
You can download the full source code of this example here: Python String Append Example

Last updated on Jan. 10th, 2022

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 19 years experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button