Open In App

Python – Fill list characters in String

Last Updated : 07 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given String and list, construct a string with only list values filled.

Input : test_str = "geeksforgeeks", fill_list = ['g', 's', 'f', k] 
Output : g__ksf__g__ks 
Explanation : All occurrences are filled in their position of g, s, f and k. 
Input : test_str = "geeksforgeeks", fill_list = ['g', 's'] 
Output : g___s___g___s 
Explanation : All occurrences are filled in their position of g and s.

Method #1: Using loop

This is a brute force approach to this problem. In this, we iterate for all the elements in a string, if it’s in list we fill it, else fill it with “space” value.

Python3




# Python3 code to demonstrate working of
# Fill list characters in String
# Using loop
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
 
# loop to iterate through string
res = ""
for chr in test_str:
 
    # checking for presence
    if chr in fill_list:
        temp = chr
    else:
        temp = "_"
    res += temp
 
# printing result
print("The string after filling values : " + str(res))


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time complexity: O(n), where n is the length of the input string “test_str”. This is because the code iterates through the elements of “test_str” one by one in a single loop using list comprehension.
Auxiliary space: O(n), where n is the length of the input string “test_str”. This is because the code creates a list of the elements of “test_str” using the “list()” function, which takes up O(n) space. Additionally, the “res” string is also of size O(n), as it is created by concatenating the elements of the list comprehension.

Method #2 : Using join() + list comprehension

The combination of the above functions can be used to solve this problem. In this, we formulate logic using list comprehension and join() is used to perform join of required values using conditions.

Python3




# Python3 code to demonstrate working of
# Fill list characters in String
# Using join() + list comprehension
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
 
# join() used to concatenate result
# using conditionals in list comprehension
res = "".join([chr if chr in fill_list else "_"
               for chr in list(test_str)])
 
# printing result
print("The string after filling values : " + str(res))


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using in, not in operators and replace() method

Python3




# Python3 code to demonstrate working of
# Fill list characters in String
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
 
# loop to iterate through string
res = ""
for i in test_str:
    if i not in fill_list:
        test_str = test_str.replace(i, "_")
# printing result
print("The string after filling values : " + str(test_str))


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time complexity: O(n^2), where n is the length of the input string. 
Auxiliary space: O(1)

Method #4: Using regular expressions:

This Python code takes a string test_str and a list fill_list as inputs. The aim of the code is to replace all the characters in the string that are not present in the list with an underscore.

To do this, the code uses the sub() method from the re module which replaces all occurrences of a given pattern with a specified string. The pattern in this case is a regular expression that includes all the characters not present in the fill_list, and the specified string is an underscore. The join() method is used to concatenate all the characters in fill_list into a string that is used to construct the regular expression.

The resulting string with the replaced characters is stored in the result variable and is printed to the console using the print() function

Python3




# importing re module
import re
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
# using sub() method of re module to fill the characters
result = re.sub("[^" + "".join(fill_list) + "]", "_", test_str)
# printing the result
print("The string after filling values : " + str(result))
# This code is contributed by Jyothi pinjala.


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time complexity: O(n), n is the length of the input string
Auxiliary space: O(n), n is the length of the input string

The space complexity of this code is O(n), where n is the length of the fill_list array. This is because the “”.join(fill_list) operation creates a new string with length k, which is used in the regular expression passed to the re.sub() method. Additionally, the result variable holds a new string of length n, which is the result of the substitution.

Method#5: Using enumeration

Algorithm:

  1. Initialize an empty string to store the result.
  2. Convert the input string into a list of characters.
  3. For each character in the list, check if it is in the fill_list using enumeration.
  4. If the character is in the fill_list, append it to the result string.
  5. If the character is not in the fill_list, append an underscore to the result string.
  6. Return the result string.

Python3




# Python3 code to demonstrate working of
# Fill list characters in String
# Using join() + enumerate()
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
 
# using enumerate() and join() to concatenate result
res = "".join([chr if chr in fill_list else "_"
               for idx, chr in enumerate(test_str)])
 
# printing result
print("The string after filling values : " + str(res))
# This code is contributed by Vinay Pinjala.


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time Complexity: O(n), where n is the length of the input string. We need to iterate over each character in the string.
Auxiliary Space: O(n), where n is the length of the input string. We need to store the result string, which can be as long as the input string.

Method #6: Using map() and lambda function

Use the map() function along with a lambda function to create a new list containing the filled characters based on the given fill list.

Approach:

  • Initialize the input string test_str to “geeksforgeeks“.
  • Print the original string using print().
  • Initialize the fill list fill_list with the characters “g”, “s”, and “f”.
  • Initialize an empty string res.
  • Start a loop to iterate through each character in the input string test_str.
    • Check if the current character chr is present in the fill list using the in operator.
    • If chr is present in fill_list, assign chr to temp.
    • If chr is not present in fill_list, assign “_” to temp.
    • Append temp to res.
  • Print the final string res using print().

Below is the implementation of the above approach:

Python3




# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
 
# creating a new list with filled characters
filled_chars = list(map(lambda c: c if c in fill_list else '_', test_str))
 
# joining the new list to form the final string
res = ''.join(filled_chars)
 
# printing result
print("The string after filling values : " + str(res))


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are creating a new list of the same length as the input string.

Method #7: Using list comprehension and ternary operator

Initialize the string “test_str” and a list “fill_list” containing the characters to be filled.
Print the original string using the “print()” function.
Use a list comprehension to create a new list “filled_chars” where each character in “test_str” is replaced with ‘_’ if it is not in “fill_list” or with the original character if it is present in “fill_list”.
Join the “filled_chars” list using the “join()” function to get the final string “res”.
Print the final string using the “print()” function.

Python3




# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing fill list
fill_list = ['g', 's', 'f']
 
# creating a new list with filled characters using list comprehension and ternary operator
filled_chars = ['_' if c not in fill_list else c for c in test_str]
 
# joining the new list to form the final string
res = ''.join(filled_chars)
 
# printing result
print("The string after filling values : " + str(res))


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time complexity: O(n), where n is the length of the input string “test_str”.
Auxiliary space: O(n), where n is the length of the input string “test_str”.

Method#8: Using Recursive method.

This code uses a recursive function fill_string which takes in the test_str and fill_list as arguments, as well as an optional idx parameter to keep track of the current index in the string.

The base case is when idx is greater than or equal to the length of the string, in which case an empty string is returned.

In the recursive case, we check whether the character at the current index is in the fill_list. If it is, we use that character, otherwise we use an underscore. We then concatenate this character with the result of calling fill_string recursively with the incremented idx.

Finally, we can call fill_string with the test_str and fill_list arguments to get the desired result.

Python3




def fill_string(test_str, fill_list, idx=0):
    if idx >= len(test_str):
        return ""
     
    if test_str[idx] in fill_list:
        temp = test_str[idx]
    else:
        temp = "_"
         
    return temp + fill_string(test_str, fill_list, idx+1)
     
test_str = "geeksforgeeks"
fill_list = ['g', 's', 'f']
res = fill_string(test_str, fill_list)
print("The original string is : " + str(test_str))
print("The string after filling values : " + res)


Output

The original string is : geeksforgeeks
The string after filling values : g___sf__g___s

Time complexity:

The function fill_string is called recursively for each character in the string test_str, so the time complexity is O(n), where n is the length of the string.
Auxiliary Space:

Since the function fill_string is called recursively, there will be n function calls on the call stack, where n is the length of the string. Therefore, the space complexity is O(n).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads