Python – Escape reserved characters in Strings List
Last Updated :
24 Mar, 2023
Given List of Strings, escape reserved characters in each String.
Input : test_list = [“Gf-g”, “be)s(t”]
Output : [‘Gf\\-g’, ‘be\\)s\\(t’]
Explanation : All reserved character elements escaped, by adding double \\.
Input : test_list = [“Gf-g”]
Output : [‘Gf\\-g’]
Explanation : All reserved character elements escaped, by adding double \\.
Method #1 : Using join() + list comprehension
In this, we construct the dictionary to map each of reserved character to its escaped version, and then perform the task of replacement in list comprehension and join the result to form Strings.
Python3
test_list = [ "Gf-g" , "is*" , "be)s(t" ]
print ( "The original list : " + str (test_list))
reserved_str =
esc_dict = { chr : f "\\{chr}" for chr in reserved_str}
res = [ ''.join(esc_dict.get( chr , chr ) for chr in sub) for sub in test_list]
print ( "The resultant escaped String : " + str (res))
|
Output
The original list : ['Gf-g', 'is*', 'be)s(t']
The resultant escaped String : ['Gf\\-g', 'is\\*', 'be\\)s\\(t']
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using join() + list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using maketrans() + translate() + zip()
In this, the escaping is made by pairing using zip() and maketrans() rather than dictionary for mapping. The translation is done using the result of maketrans().
Python3
test_list = [ "Gf-g" , "is*" , "be)s(t" ]
print ( "The original list : " + str (test_list))
reserved_chars =
mapper = [ '\\' + ele for ele in reserved_chars]
result_mapping = str .maketrans( dict ( zip (reserved_chars, mapper)))
res = [sub.translate(result_mapping) for sub in test_list]
print ( "The resultant escaped String : " + str (res))
|
Output
The original list : ['Gf-g', 'is*', 'be)s(t']
The resultant escaped String : ['Gf\\-g', 'is\\*', 'be\\)s\\(t']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n2)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...