Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

python - 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 it replaces it with box1 instead of the values 55, 55.7

box1 = 55, 55.7
box2 = -9, -7

with open('parttest', 'r') as file :
    filedata = file.read()

filedata = filedata.replace('box_lat', 'box1')
filedata = filedata.replace('box_lon', 'box2')

with open('buildtest', 'w') as file:
    file.write(filedata)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('()'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...