如何用字典替换字符串中缺少的字符

2024-10-01 09:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用字典替换字符串中缺少的字符。以t-a-19-/为例。我想用数组中所有可能的字母或数字替换破折号。你知道吗

我尝试使用replace()函数,但它不能接受数组。我如何使用数组执行相同的函数?你知道吗

这是我的密码:

word = "t-a-19-/"

# Alpha numeric dictionary
alphanumericdict = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

# Replaces string with dictionary
brute = word.replace('-', alphanumericdict);
print(brute);

我得到这个错误是因为replace()函数只接受字符串,而不接受列表。你知道吗

Traceback (most recent call last):
  File "bruteforce.py", line 17, in <module>
    brute = word.replace('-', alphanumericdict);
TypeError: replace() argument 2 must be str, not list

Tags: 函数字符串alpha密码dictionary字典字母数字
1条回答
网友
1楼 · 发布于 2024-10-01 09:23:56

你可以这样做:

import itertools
import string
letters = string.ascii_lowercase #'abcdefg....'

for c1,c2,c3 in itertools.product(letters, repeat=3):
    print(word.replace('-','%s')%(c1,c2,c3))

输出:

taaa19a/
taaa19b/
taaa19c/
taaa19d/
taaa19e/
.
.
.
tzaz19v/
tzaz19w/
tzaz19x/
tzaz19y/
tzaz19z/

相关问题 更多 >