Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何用字典替换字符串中缺少的字符_Python - Fatal编程技术网

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

Python 如何用字典替换字符串中缺少的字符,python,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',

我想用字典替换字符串中缺少的字符。以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
回溯(最近一次呼叫最后一次):
文件“bruteforce.py”,第17行,在
brute=单词.replace('-',字母数字分词);
TypeError:replace()参数2必须是str,而不是list

您可以这样做:

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/

你的
alphanumericdict
是一个列表,而不是一本字典——你想实现什么(brute应该是什么?)你期望得到什么结果?您知道dict和list之间的区别吗?alphanumericidct是一个列表,顺便说一句。但您是说您想生成从taaa19a/到tzaz19z的所有选项/?字典包含一个大括号内的键值对。方括号是一个列表。我想你需要类似于
brute=[word.replace(“-”,I)的东西来代替d中的I]
。回答得好。顺便说一句,你不必写
字母
,因为
str
已经是一个iterable:
itertools.product(ascii\u小写,repeat=3)
工作得很好你是对的。。我应该想到的,谢谢