将字符串转换为切片索引并为其分配值

问题描述 投票:0回答:2

示例:

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

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

我做的第一件事是创建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
2个回答
2
投票

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

根据您的注释的要求,如果字符串为"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
投票

使用Pyhon的slice对象:

slice

P.S。请遵循Python的[[naming约定(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 是错误的示例)。

© www.soinside.com 2019 - 2024. All rights reserved.