0

I want to traverse the for loop to find all the occurrences of "%" followed by an integer and replace them with another word.

 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

If there is more than one "%" in format(i.e string) then only integer, is getting replaced.

Eg: format : "%1 greets %0" and args = "Bob", "Alex"

The output should be : "Alex greets Bob"

But what I'm getting is "Alex greets %0"

1
  • find() will only return the index of first occurance. Why dont you simply use a regex. m = re.search('%\d', format) Commented Jul 5, 2018 at 11:46

3 Answers 3

3

You need to write if x == "%", instead if x is "%". The is operator checks if they are actually the same object, not if they have the same content.

Another problem is the the .find('%') always returns the position of the first % in the string, regardless of where you are in you iteration. You could change your code to something like

for finder, x in enumerate(format):
     if x is "%":
         # you already know your position
         val = format[finder+1]
         ...
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is not solved yet. Eg: format = "Hello %0, %1" args = "Bob", "Alex" , it is still returning the same: "Hello Bob, 1".
1

Your problem is in this line if x is "%":, is operator checks whether the both are same object. You need to use if x=='%' (== operator checks whether both are same value or not, it's not necessary to be both the same object to return True).

1 Comment

The problem is not solved yet. Eg: format = "Hello %0, %1" args = "Bob", "Alex" , it is still returning the same: "Hello Bob, 1".
0

There are definitely better ways of doing this, but if you want to do it with a loop then this will work.

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)

Your solution doesn't work because you keep searching the same string (format) but saving the result in another string (str). The find method will therefore always find the first % in the format string.

One more comment i would like to add is to avoid naming your variables as python keywords like format and str.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.