通过在列表前面添加反斜杠来转义列表中的保留字符 - python

reserved_chars = "? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -"

list_vals = ['[email protected]', 'P&[email protected]', 'JACKSON! BOT', 'annoying\name']

循环遍历列表中的每个元素并在其中一个包含保留字符的前面添加\的最快方法是什么?

所需的输出:

fixed_list = ['gold\[email protected]', 'P\&[email protected]', 'JACKSON\! BOT', 'annoying\\name']

参考方案

您可以使用str.maketrans()制作翻译表,并将其传递给翻译。这需要一些设置,但是您可以重复使用转换表,而且速度非常快:

reserved_chars = '''?&|!{}[]()^~*:\\"'+-'''
list_vals = ['[email protected]', 'P&[email protected]', 'JACKSON! BOT', 'annoying\\name']

# make trans table
replace = ['\\' + l for l in reserved_chars]
trans = str.maketrans(dict(zip(reserved_chars, replace)))

# translate with trans table
fixed_list = [s.translate(trans) for s in list_vals]

print("\n".join(fixed_list))

印刷品:

gold\[email protected]
P\&[email protected]
JACKSON\! BOT
annoying\\name

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

Matplotlib'粗体'字体 - python

跟随this example:import numpy as np import matplotlib.pyplot as plt fig = plt.figure() for i, label in enumerate(('A', 'B', 'C', 'D')): ax = f…