Python | Append suffix/prefix to strings in list
Last Updated :
03 May, 2023
Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed.
Method #1: Using + operator + list comprehension In this task, we just append the string at rear or front position using + operator and list comprehension is used to iterate through all the elements.
Python3
# Python3 code to demonstrate working of
# Append suffix / prefix to strings in list
# Using list comprehension + "+" operator
# initializing list
test_list = ['a', 'b', 'c', 'd']
# printing list
print("The original list : " + str(test_list))
# initializing append_str
append_str = 'gfg'
# Append suffix / prefix to strings in list
pre_res = [append_str + sub for sub in test_list]
suf_res = [sub + append_str for sub in test_list]
# Printing result
print("list after prefix addition : " + str(pre_res))
print("list after suffix addition : " + str(suf_res))
Output :
The original list : ['a', 'b', 'c', 'd']
list after prefix addition : ['gfga', 'gfgb', 'gfgc', 'gfgd']
list after suffix addition : ['agfg', 'bgfg', 'cgfg', 'dgfg']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using itertools.starmap(): The python library itertools provides a function called "starmap()" which can be used to apply the same function to multiple inputs from an iterable, in this case, it can be used to append the suffix/prefix to each string in the list, this approach would have a time complexity of O(n) and auxiliary space of O(n) as well.
Python3
#Using itertools.starmap()
import itertools
#initializing list
test_list = ['a', 'b', 'c', 'd']
#printing original list
print("The original list :", test_list)
#initializing append_str
append_str = 'gfg'
#Append suffix / prefix to strings in list
pre_res = list(itertools.starmap(lambda s: append_str + s, test_list))
suf_res = list(itertools.starmap(lambda s: s + append_str, test_list))
#Printing result
print("list after prefix addition :", pre_res)
print("list after suffix addition :", suf_res)
OutputThe original list : ['a', 'b', 'c', 'd']
list after prefix addition : ['gfga', 'gfgb', 'gfgc', 'gfgd']
list after suffix addition : ['agfg', 'bgfg', 'cgfg', 'dgfg']
Method #3: Using map and lambda functions
Python3
def add_prefix_suffix(lst, prefix, suffix):
pre_res = list(map(lambda x: prefix + x, lst))
suf_res = list(map(lambda x: x + suffix, lst))
return pre_res, suf_res
test_list = ['a', 'b', 'c', 'd']
print("The original list :", test_list)
pre_res, suf_res = add_prefix_suffix(test_list, 'gfg', 'gfg')
print("list after prefix addition :", pre_res)
print("list after suffix addition :", suf_res)
#This code is contributed by Vinay Pinjala.
OutputThe original list : ['a', 'b', 'c', 'd']
list after prefix addition : ['gfga', 'gfgb', 'gfgc', 'gfgd']
list after suffix addition : ['agfg', 'bgfg', 'cgfg', 'dgfg']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using For loop.
Python3
test_list = ['a', 'b', 'c', 'd']
prefix,suffix='gfg', 'gfg'
print("The original list :", test_list)
pre_res = []
suf_res = []
for item in test_list:
pre_res.append(prefix + item)
suf_res.append(item + suffix)
print("list after prefix addition :", pre_res)
print("list after suffix addition :", suf_res)
#This code is contributed by tvsk.
OutputThe original list : ['a', 'b', 'c', 'd']
list after prefix addition : ['gfga', 'gfgb', 'gfgc', 'gfgd']
list after suffix addition : ['agfg', 'bgfg', 'cgfg', 'dgfg']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using numpy module:
Step-by-step approach:
- Initialize an empty list to store the result of prefix addition and another empty list to store the result of suffix addition.
- Iterate through the original list, and for each element, append the prefix to the beginning of the element and append the result to the prefix addition list.
- Similarly, append the suffix to the end of the element and append the result to the suffix addition list.
- Print the original list, prefix addition list, and suffix addition list.
Python3
import numpy as np
# initializing list
test_list = ['a', 'b', 'c', 'd']
prefix,suffix='gfg', 'gfg'
pre_res = np.char.add(prefix, test_list)
suf_res = np.char.add(test_list, suffix)
# printing list
print("The original list :", test_list)
# Printing result
print("list after prefix addition :", pre_res)
print("list after suffix addition :", suf_res)
#This code is contributed by Jyothi Pinjala.
Output:
The original list : ['a', 'b', 'c', 'd']
list after prefix addition : ['gfga' 'gfgb' 'gfgc' 'gfgd']
list after suffix addition : ['agfg' 'bgfg' 'cgfg' 'dgfg']
Time complexity: O(n), where n is the number of elements in the input list. This is because we iterate through each element once to perform the prefix and suffix addition.
Auxiliary Space: O(n), where n is the number of elements in the input list. This is because we create two lists of size n to store the results of the prefix and suffix addition
Method #6: Using the reduce() function from the functools module
Step-by-step approach:
- Import the reduce() function from the functools module.
- Create a test_list of strings.
- Create two variables prefix and suffix with the desired string values.
- Use the reduce() function with a lambda expression to iterate through each element item in test_list, concatenate prefix to it, and append the result to pre_res.
- Use the reduce() function with a lambda expression to iterate through each element item in test_list, concatenate suffix to it, and append the result to suf_res.
- Print the original list, test_list, the list after prefix addition, pre_res, and the list after suffix addition, suf_res.
Python3
from functools import reduce
test_list = ['a', 'b', 'c', 'd']
prefix, suffix = 'gfg', 'gfg'
pre_res = reduce(lambda res, item: res + [prefix + item], test_list, [])
suf_res = reduce(lambda res, item: res + [item + suffix], test_list, [])
print("The original list :", test_list)
print("List after prefix addition :", pre_res)
print("List after suffix addition :", suf_res)
OutputThe original list : ['a', 'b', 'c', 'd']
List after prefix addition : ['gfga', 'gfgb', 'gfgc', 'gfgd']
List after suffix addition : ['agfg', 'bgfg', 'cgfg', 'dgfg']
Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(n), where n is the length of test_list.
Similar Reads
Python | Append String to list
Sometimes, while working with data, we can have a problem in which we need to add elements to a container. The list can contain any type of data type. Let's discuss certain ways in Python in which we can perform string append operations in the list of integers.Example: Append String at the end of a
5 min read
Prefix frequency in string List - Python
In this article, we will explore various methods to find prefix frequency in string List. The simplest way to do is by using a loop.Using a LoopOne of the simplest ways to calculate the frequency of a prefix in a list of strings is by iterating through each element and checking if the string starts
2 min read
How to Append to String in Python ?
In Python, Strings are immutable datatypes. So, appending to a string is nothing but string concatenation which means adding a string at the end of another string.Let us explore how we can append to a String with a simple example in Python.Pythons = "Geeks" + "ForGeeks" print(s)OutputGeeksForGeeks N
2 min read
List of strings in Python
A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Create a List of Strings in Python
Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Python | Check if suffix matches with any string in given list
Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task
6 min read
Python | Delimited String List to String Matrix
Sometimes, while working with Python strings, we can have problem in which we need to convert String list which have strings that are joined by deliminator to String Matrix by separation by deliminator. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + split() T
5 min read
Tokenizing Strings in List of Strings - Python
The task of tokenizing strings in a list of strings in Python involves splitting each string into smaller units, known as tokens, based on specific delimiters. For example, given the list a = ['Geeks for Geeks', 'is', 'best computer science portal'], the goal is to break each string into individual
2 min read
Python | Split strings in list with same prefix in all elements
Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let's discuss certain ways in which this problem can be solved. Method #1 : Usin
5 min read
Python | Ways to merge strings into list
Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requir
4 min read