Python - Conditional String Append
Last Updated :
09 Apr, 2023
Sometimes, while working with data, we have a problem in which we need to perform an append operation in a string on a particular condition. This kind of problem is common in web development and day-day programming. Let's discuss certain ways in which this task can be performed.
Method #1: Using loop This is a brute-force way to perform this task. In this, we run a loop and check for the condition, and according to that append the string to the original string.
Python3
# Python3 code to demonstrate
# Conditional String Append
# using loop
def append_str(item, boy_str, girl_str):
if len(item) > 4 and item[-5] == ' ':
return item + girl_str
return item + boy_str
# initializing list
test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
# initializing append string
boy_str = " Boy"
girl_str = " Girl"
# printing original list
print ("The original list is : " + str(test_list))
# Conditional String Append
# using loop
res = [append_str(item, boy_str, girl_str) for item in test_list]
# printing result
print ("The filtered strings are : " + str(res))
OutputThe original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using list comprehension List comprehension is shorthand for the longer method of loops. This solved problem in similar way but in shorter constructs.
Python3
# Python3 code to demonstrate
# Conditional String Append
# using list comprehension
# initializing list
test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
# initializing append string
boy_str = " Boy"
girl_str = " Girl"
# printing original list
print ("The original list is : " + str(test_list))
# Conditional String Append
# using list comprehension
res = [ele + girl_str if ele[-5] == ' ' else ele + boy_str for ele in test_list]
# printing result
print ("The filtered strings are : " + str(res))
OutputThe original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using map function Map function is used to create a new list by updating the existing list. We solve this problem by defining the condition append function for the map function which will apply to all the elements of the list.
Python3
# # Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using map
# Initializing append string
boy_str = " Boy"
girl_str = " Girl"
# Function to append the string
def func(x):
if x[-5] == ' ':
return x + girl_str
else:
return x + boy_str
# initializing list
test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
# printing original list
print("The original list is : " + str(test_list))
# Conditinal string append using map
res = list(map(func, test_list))
# printing result
print("The filtered string are : " + str(res))
OutputThe original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered string are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach#4: Using regular expression
This Approach uses regular expressions to match strings ending with "Singh" and appends "Boy" to those strings. For other strings, it appends "Girl". The filtered strings are stored in a new list called "filtered_strings".
Algorithm
1. Import the re module for regular expressions
2. Define a regular expression pattern to match strings ending with 'Singh'
3. Create an empty list 'filtered_strings'
4. Iterate over each string in the original list:
a. Use the re.sub() function to replace the matched pattern with 'Boy' and append it to 'filtered_strings'
b. If the pattern does not match, append the string with 'Girl' and add it to 'filtered_strings'
5. Return the 'filtered_strings' list
Python3
import re
original_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
pattern = re.compile(r'Singh$')
filtered_strings = []
for string in original_list:
if pattern.search(string):
filtered_strings.append(pattern.sub('Boy', string))
else:
filtered_strings.append(string + ' Girl')
print('The filtered strings are:', filtered_strings)
OutputThe filtered strings are: ['Manjeet Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']
Time complexity: O(n), where n is the length of the original list. We iterate over each string in the list once.
Auxiliary Space: O(n), where n is the length of the original list. We create a new list 'filtered_strings' which stores n strings. We also create a regular expression pattern object, which takes up some memory.
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
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
Python - Alternate Strings Concatenation The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Letâs discuss certain ways in which this can be performed. Met
3 min read
String Interning in Python String interning is a memory optimization technique used in Python to enhance the efficiency of string handling. In Python, strings are immutable, meaning their values cannot be changed after creation. String interning, or interning strings, involves reusing existing string objects rather than creat
2 min read
In-Place String Modifications in Python Strings are immutable in Python, meaning their values cannot be modified directly after creation. However, we can simulate in-place string modifications using techniques such as string slicing and conversion to mutable data types like lists.Using String SlicingString slicing is one of the most effic
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