Skip to content Skip to sidebar Skip to footer

Str.replace With A Variable

This is probably a simple fix, but having a little trouble getting my head around it; I'm reading lines from a different script, and want to replace a line with a variable, however

Solution 1:

You currently are replacing those values with the literal name of the variable. If you want it to use the values that those variable names refer to, omit the quotes.

Next, you'll have to turn those variables into strings, because I suspect that the reason you used quotes in the first place was because you got an error without them, as well. This is because replace takes only strings, and your variables are tuples. To fix this, cast the variable to a string.

filedata = filedata.replace('box_lat', str(box1))

If you don't want to keep the parentheses that appear in a string representation of a tuple, you can strip them off:

filedata = filedata.replace('box_lat', str(box1).strip('()'))

Solution 2:

If you want to replace with the value of the variable box1 you need to remove the quotes surrounding it. Try:

box1 = "55, 55.7"box2 = "-9, -7"filedata = filedata.replace('box_lat', box1)
filedata = filedata.replace('box_lon', box2)

Quotes will replace with the text enclosed; whereas, a variable name should not be in quotes.

Solution 3:

As @tigerhawk and @sam said if you enter something in quotes it means the literal thing you typed in the quotes so try removing the quotes around 'box 1'

Post a Comment for "Str.replace With A Variable"