繁体   English   中英

for循环未在python中完全迭代

[英]the for loop is not iterating completely in python

我想遍历for循环以查找所有出现的“%”后跟一个整数,然后用另一个单词替换它们。

 for x in format:
     if x is "%":
         finder = format.find("%")
         val = format[finder + 1]
         index = int(format[finder + 1])
         print("Index value is %d" % index)
         replace = args[index]
         print(replace)
         str = format.replace(val, replace)
 return str

如果格式(即字符串)中有多个“%”,则仅替换整数。

例如:格式: "%1 greets %0" and args = "Bob", "Alex"

输出应为: "Alex greets Bob"

但是我得到的是"Alex greets %0"

if x == "%"if x is "%"需要编写, if x is "%"if x is "%"需要编写。 is运算符检查它们是否实际上是同一对象,而不是它们是否具有相同内容。

另一个问题是.find('%')始终返回字符串中第一个%的位置,而不管您在迭代中的位置如何。 您可以将代码更改为

for finder, x in enumerate(format):
     if x is "%":
         # you already know your position
         val = format[finder+1]
         ...

你的问题是在这条线if x is "%": is运营商检查是否都是同一个对象。 您需要使用if x=='%'==运算符检查两者是否都相同,不必都是相同的对象来返回True )。

绝对有更好的方法可以执行此操作,但是如果您想循环执行此操作,则可以使用。

item = '%1 greets %0'
args = ['bob','alex']
loc = 0
for x in item:  
    if x == "%":
        loc = item.find("%",loc)
        val ='%'+ item[loc +1]
        index = int(item[loc +1])
        replace = args[index]
        item = item.replace(val,replace)
        loc +=1

print(item)

您的解决方案不起作用,因为您一直在搜索相同的字符串(格式),但将结果保存在另一个字符串(str)中。 因此,find方法将始终在格式字符串中找到第一个%。

我想补充的另一条评论是避免将变量命名为python关键字,例如format和str。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM