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

问题描述 投票:0回答:2
#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

OUTPUT:

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'

python string python-3.x for-loop
2个回答
2
投票

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

如果我理解你想要做什么,那就像是

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

-1
投票

我对你的fix_start函数做了一些修改:

def fix_start(s):
   a = s[0]
   return a + s[1:].replace(a, '*')

a = s[0]将字符串的第一个元素分配给变量as[1:]从字符串中删除第一个元素。 return a + s[1:].replace(a, '*')a添加到修改后的字符串并返回结果。通过这些更改,您可以获得所需的输出:ba**le

© www.soinside.com 2019 - 2024. All rights reserved.