gpt4 book ai didi

python - 更好地替换巨大的 “if x==2/if x==3/if x==4” 链删除前缀和后缀?

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:49 24 4
gpt4 key购买 nike

我是Python新手。我正在制作一个简单的解密系统。我想要删除第一个字符和最后 4 个或 5 个字符(取决于密码的长度)。我唯一能弄清楚的就是用 if 语句来做到这一点:(。有更好的方法吗?如果有的话有人可以解释一下吗?

if (len(initialPass)) == 2 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:2]
if (len(initialPass)) == 3 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:3]
if (len(initialPass)) == 4 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:4]
if (len(initialPass)) == 5 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:5]
if (len(initialPass)) == 6 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:6]
if (len(initialPass)) == 7 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:7]
if (len(initialPass)) == 8 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:8]
if (len(initialPass)) == 9 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:9]
if (len(initialPass)) == 10 + 5:
initialPass = initialPass[1:]
initialPass = initialPass[:10]
if (len(initialPass)) == 11 + 6:
initialPass = initialPass[2:]
initialPass = initialPass[:11]
if (len(initialPass)) == 12 + 6:
initialPass = initialPass[2:]
initialPass = initialPass[:12]
if (len(initialPass)) == 13 + 6:
initialPass = initialPass[2:]
initialPass = initialPass[:13]
if (len(initialPass)) == 14 + 6:
initialPass = initialPass[2:]
initialPass = initialPass[:14]
if (len(initialPass)) == 15 + 6:
initialPass = initialPass[2:]
initialPass = initialPass[:15]
if (len(initialPass)) == 16 + 7:
initialPass = initialPass[2:]
initialPass = initialPass[:16]
if (len(initialPass)) == 17 + 7:
initialPass = initialPass[2:]
initialPass = initialPass[:17]
if (len(initialPass)) == 18 + 7:
initialPass = initialPass[2:]
initialPass = initialPass[:18]
if (len(initialPass)) == 19 + 7:
initialPass = initialPass[2:]
initialPass = initialPass[:19]
if (len(initialPass)) == 20 + 7:
initialPass = initialPass[2:]
initialPass = initialPass[:20]

最佳答案

发布@Woody Pride 的解决方案作为答案:这相当于 Python 中的所有代码:

initialPass = initialPass[1 if len(initialPass) <= 15 else 2:-4]

说明:Python 的切片使用负索引。它的定义如下:

sublist = list[start:end:step]

和负值将被解释为从末尾开始计数。请注意,索引从 0 开始。因此 "Hamster"[1]a。这里有一些更多的例子来澄清问题:

"Hamster"[1:3]  = "am"
"Hamster"[2:] = "mster"
"Hamster"[-2:] = "er"
"Hamster"[2:-2] = "mst"
"Hamster"[::2] = "Hmtr"

关于python - 更好地替换巨大的 “if x==2/if x==3/if x==4” 链删除前缀和后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32575918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com