Python String Append

String append in python; Through this tutorial, i am going to show you how to append one string to another string in python.

Python String Append

Use + operator to concatenate or join two strings in python and created a new string in python.

Let’s look at a function to join a string ‘n’ times:

def str_append(s, n):
    output = ''
    i = 0
    while i < n:
        output += s
        i = i + 1
    return output

Notice:- that I am defining this function to showcase the usage of + operator. I will later use timeit module to test the performance. If you simply want to concatenate a string ‘n’ times, you can do it easily using s = 'Hi' * 10.

Another way to join/concatenate string append operation is by creating a python list and appending strings to the python list. Then use python string join() function to join/merge string and list together to get the result string.

def str_append_list_join(s, n):
    l1 = []
    i = 0
    while i < n:
        l1.append(s)
        i += 1
    return ''.join(l1)

Let’s examine these methods to make sure they are working as supposed.

if __name__ == "__main__":
    print('Append using + operator:', str_append('Hi', 10))
    print('Append using list and join():', str_append_list_join('Hi', 10))
    # use below for this case, above methods are created so that we can
    # check performance using timeit module
    print('Append using * operator:', 'Hi' * 10)

Output:

Append using + operator: HiHiHiHiHiHiHiHiHiHi
Append using list and join(): HiHiHiHiHiHiHiHiHiHi
Append using * operator: HiHiHiHiHiHiHiHiHiHi

A simple way to append strings in Python

You need to have both the methods defined in string_append.py file. Let’s use time it module to check their performance.

$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hello", 1000)' 
1000 loops, best of 5: 174 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hello", 1000)'
1000 loops, best of 5: 140 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hi", 1000)' 
1000 loops, best of 5: 165 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hi", 1000)'

Recommended Python Tutorials

Recommended:-Python Map() Method

Leave a Comment