python - 迭代具有不同可能字符的字符串

标签 python python-3.4

我刚刚在这里注册,因为我正在参加 Python 在线类(class),并且一直在使用这个网站来帮助我完成类(class)。我是;然而,卡住了。

我没有发布我的实际家庭作业,而只是我遇到困难的代码元素......

我正在尝试使用包含字母表中字母的列表来遍历字符串。我想让列表中的每个字母遍历不同索引处的单词。例如:

word = " Pandas " char_list = ['a','b','c'] 等等... 输出应该是aanda, panda, paada ...... 接着是banda,pbnda,pabda,...

我的代码只使用列表中的第一个字符遍历单词。 抱歉,我对一般的编码非常陌生......

index = 0
word = "panda"
possible_char = ['a', 'b', 'c', 'd', 'o']
for char in possible_char:
    while index < len(word):
        new_word = word[:index] + char + word[index + 1:]
        print (new_word)
        index = index + 1

最佳答案

您的 while 循环仅适用于外部 for 循环的第一次迭代,因为 index 不会重置并保持在 len(word) 第一次完成后。尝试将初始化它的行移动到外循环内的 0:

for char in possible_chars:
    index = 0
    while index < len(word):
        #...

关于python - 迭代具有不同可能字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35666323/

相关文章:

apache-spark - JavaPackage 对象不可调用错误 : Pyspark

python - python中的生产者消费者算法

python - Python 中带有额外参数的父方法

python - 按照字符串中的格式用日期时间填充 python 字符串

python - scipy.linalg.svd : shapes of VT and U: what is full_matrices and why is it needed?

ipython - "import matlab.engine"适用于 Linux 命令行,但不适用于 Spyder

python - 删除列表中前 N 个元素的最有效方法?

python - 如何使用 NodeJS 在单个 HTTP POST 中发送文件和 JSON 数据(元数据)

python - 在 Mac OS 10.9 上为 Python 3.4 安装 nltk

python - 为什么 `try ... except` 比 `if` 快?