0

I wrote a code which is meant to replace a tag from a string with a number extracted from an array.

This is part of a bigger project but I only isolated the problematic part

# import numpy as np
time_vect = np.arange(0, 10, 1)
string = "T= <T>"
for i in range(0, len(time_vect),1):
    string = string.replace("<T>", str(time_vect[i]))
    print(string)

However the replace function seems to totally ignore the value. When I run the code I get this output :

T= 0
T= 0
T= 0
T= 0
T= 0
T= 0
T= 0
T= 0
T= 0
T= 0

When I assign the value manually, I get the expected result

>> print(string.replace("<T>", str(time_vect[3])))
T= 3

I tried to convert the numpy.int32 type into native int type but it did not solve the problem

string = string.replace("<T>", str(time_vect[i].item()))

I could not find any leads on the net so I would be thankful if I could get some support :)

1
  • 2
    You are replacing the "<T>" in the first iteration, after that the replace function can't find it again. Commented Jul 14, 2021 at 10:47

2 Answers 2

1

Same as @Vulwsztyn, without an intermediate variable :

time_vect = np.arange(0, 10, 1)
string = "T= <T>"
for i in range(0, len(time_vect),1):
    print(string.replace("<T>", str(time_vect[i])))
Sign up to request clarification or add additional context in comments.

1 Comment

Well noted ! Thanks
0

You cannot reassing string in the loop. After the first iteration, your string no longer contains <T> so there is nothing to replace it is "T= 0", so replacing <T> does nothing.

import numpy as np
time_vect = np.arange(0, 10, 1)
string = "T = <T>"
for i in range(0, len(time_vect),1):
    s = string.replace("<T>", str(time_vect[i]))
    print(s)

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.