Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...