📜  Python – 转义字符串列表中的保留字符

📅  最后修改于: 2022-05-13 01:55:34.799000             🧑  作者: Mango

Python – 转义字符串列表中的保留字符

给定字符串列表,转义每个字符串中的保留字符。

方法 #1:使用 join() + 列表推导

在此,我们构造字典以将每个保留字符映射到其转义版本,然后在列表理解中执行替换任务并将结果连接起来形成字符串。

Python3
# Python3 code to demonstrate working of
# Escape reserved characters in Strings List
# Using list comprehension + join()
 
# initializing list
test_list = ["Gf-g", "is*", "be)s(t"]
 
# printing string
print("The original list : " + str(test_list))
 
# the reserved string
reserved_str = """? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -"""
 
# the mapped escaped values
esc_dict = { chr : f"\\{chr}" for chr in reserved_str}
 
# performing transformation using join and list comprehension
res = [ ''.join(esc_dict.get(chr, chr) for chr in sub) for sub in test_list]
 
# printing results
print("The resultant escaped String : " + str(res))


Python3
# Python3 code to demonstrate working of
# Escape reserved characters in Strings List
# Using maketrans() + translate() + zip()
 
# initializing list
test_list = ["Gf-g", "is*", "be)s(t"]
 
# printing string
print("The original list : " + str(test_list))
 
# reserved_chars
reserved_chars = '''?&|!{}[]()^~*:\\"'+-'''
 
# the escaping logic
mapper = ['\\' + ele for ele in reserved_chars]
result_mapping = str.maketrans(dict(zip(reserved_chars, mapper)))
 
# reforming result
res = [sub.translate(result_mapping) for sub in test_list]
 
# printing results
print("The resultant escaped String : " + str(res))


输出
The original list : ['Gf-g', 'is*', 'be)s(t']
The resultant escaped String : ['Gf\\-g', 'is\\*', 'be\\)s\\(t']

方法 #2:使用 maketrans() + translate() + zip()

在这种情况下,转义是通过使用 zip() 和 maketrans() 而不是字典进行映射来进行的。翻译是使用 maketrans() 的结果完成的。

Python3

# Python3 code to demonstrate working of
# Escape reserved characters in Strings List
# Using maketrans() + translate() + zip()
 
# initializing list
test_list = ["Gf-g", "is*", "be)s(t"]
 
# printing string
print("The original list : " + str(test_list))
 
# reserved_chars
reserved_chars = '''?&|!{}[]()^~*:\\"'+-'''
 
# the escaping logic
mapper = ['\\' + ele for ele in reserved_chars]
result_mapping = str.maketrans(dict(zip(reserved_chars, mapper)))
 
# reforming result
res = [sub.translate(result_mapping) for sub in test_list]
 
# printing results
print("The resultant escaped String : " + str(res))
输出
The original list : ['Gf-g', 'is*', 'be)s(t']
The resultant escaped String : ['Gf\\-g', 'is\\*', 'be\\)s\\(t']