【问题标题】:Transforming a string to a slice indice and assign a value to it将字符串转换为切片索引并为其赋值
【发布时间】:2019-11-10 11:44:07
【问题描述】:

例子:

sb = "Washington"
removecharsDB = [":2","-1:"]

我想要做的是使用removecharsDB 删除sb 的一部分。

我做的第一件事是创建sb 的列表。

r = list(sb)
r
['W', 'a', 's', 'h', 'i', 'n', 'g', 't', 'o', 'n'] 

然后

r[:2] = ""
r[-1:] = ""
"".join(r)

结果:“shingto”

但我想动态地做。

for n in removecharsDB:
   r[eval(n)] = ""

SyntaxError: invalid syntax

for n in removecharsDB:
    r + eval("[" + n + "]") = ""

SyntaxError: can't assign to operator

for n in removecharsDB:
    eval("r[" + n + "]") = ""

SyntaxError: can't assign to function call

如何将字符串转换为切片索引?

【问题讨论】:

标签: python python-3.x list slice


【解决方案1】:

您可以解析字符串":2" 和"-1:" 以提取切片的开始和结束。请注意,切片表示法中的空值与 None 相同。

根据您的评论要求,如果字符串为"3",我们可以生成要替换的切片[3:4]。

所以,你可以这样做:

sb = "Washington"
removecharsDB = [":2","-1:", "3"]

slices = [[int(val) if val else None for val in s.split(':')]
          if ':' in s else [int(s), int(s)+1 or None] for s in removecharsDB]
# print(slices)
# [[None, 2], [-1, None], [3, 4]]

r = list(sb)
for start, stop in slices:
    r[start:stop] = []

print("".join(r))
# shigto

【讨论】:

  • +1 ,因为这比 eval() 方法好得多,因为它可以安全地处理 removecharsDB 的无效和潜在危险内容。
  • 谢谢蒂埃里。它工作正常,但如果 removecharsDB 有数字作为元素 p.e. removecharsDB = ["0","2","-1:"]
  • 我更新了单索引情况的答案。
  • @ThierryLathuille 谢谢。我在我的例子中做错了什么?难道不能用 eval() 吗?
  • eval 只能计算表达式(如x+1),仅此而已。你可以使用exec:exec("r[" + n + "] = []") - 但不要! ;)
【解决方案2】:

使用 Pyhon 的 slice 对象:

s = "Washington"
s_lst = list(s)
removechars_lst = [":2","-1:"]

for sl in removechars_lst:
    s_lst[slice(*[int(i) if i else None for i in sl.split(':')])] = ''

print(''.join(s_lst))   # shingto

附:请遵循 Python 命名 约定(removecharsDB 是一个不好的示例)。

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2015-05-15
    • 2017-02-19
    相关资源
    最近更新 更多