python - 对于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()
输出:
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 中,字符串是可迭代的。因此,您的行将for i in s
运行n次,字符串中的每个字母一个,并且将打印“未找到”。循环第一次运行时,它替换a
为*
. 因此,对于所有后续运行,它将打印“未找到”。
如果我了解您要做什么,那将是
first_letter = s[0]
rest_string = s[1:].replace(first_letter, '*')
new_string = first_letter + rest_string
推荐阅读
- here-api - 根据交通状况访问和着色特定车道
- scrapy - Scrapy - 蜘蛛调度
- asp.net-mvc - d3 sunburst zoom 在 html 中工作,但在 mvc 视图中不工作
- node.js - 循环播放文件 discord.js
- javascript - javascript没有为上传的CSV中的所有记录调用ajax
- anylogic - Anylogic交通软件参数未指定
- ag-grid - Ag-Grid:将列的位置锁定到最后一列
- apache-beam - apache-beam 使用的最新版本的 jdk 是什么
- arrays - VBA:尽管没有数组,但预期的数组错误
- django - “如何修复”在 django 中没有名为“核心”的模块”