str.replace 一个变量 [英] str.replace with a variable

查看:45
本文介绍了str.replace 一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的解决方法,但在理解它时有点困难;我正在从不同的脚本中读取行,并想用变量替换一行,但是它用 box1 而不是值 55, 55.7

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)

推荐答案

您当前正在用变量的字面名称替换这些值.如果您希望它使用这些变量名称所引用的值,请省略引号.

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.

接下来,您必须将这些变量转换为字符串,因为我怀疑您首先使用引号的原因是因为没有它们也会出现错误.这是因为 replace 只接受字符串,而你的变量是 tuples.要解决此问题,请将变量强制转换为字符串.

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

如果您不想保留出现在 tuple 的字符串表示中的括号,您可以将它们去掉:

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

这篇关于str.replace 一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆