首页 > 解决方案 > 对于python索引字符串和搜索字符串中的循环,任何人都可以解释输出

问题描述

#usr/bin/python 3.6.1
import sys

def fix_start(s):
    a = s[0]

    i=1
    for i in s:
        if a in s :
            print("found")
            s=s.replace(a,'*')
        else: print (" not found")

    return (s)

def main():
    c = fix_start(sys.argv[1])
    print (c)

if __name__=='__main__':
    main()

enter image description here

输出:

C:\Users\pavithra.sridhar\Downloads\google-python-exercises\basic>python FixString.py babble
found
not found
not found
not found
not found
not found
*a**le

对于命令行参数“babble”,

预期产出

Ba**le

用 * 替换第二次出现的其余部分。

谁能解释为什么它多次打印“未找到”的逻辑。

但所需的输出是:输入 Babble 的 'Ba**le'

标签: pythonstringpython-3.xfor-loop

解决方案


在 python 中,字符串是可迭代的。因此,您的行将for i in s运行n次,字符串中的每个字母一个,并且将打印“未找到”。循环第一次运行时,它替换a*. 因此,对于所有后续运行,它将打印“未找到”。

如果我了解您要做什么,那将是

first_letter = s[0]
rest_string = s[1:].replace(first_letter, '*')
new_string = first_letter + rest_string

推荐阅读