【问题标题】:str.replace with a variablestr.replace 用一个变量
【发布时间】:2016-01-11 19:38:15
【问题描述】:

这可能是一个简单的解决方法,但是我很难理解它;我正在从不同的脚本中读取行,并想用变量替换一行,但是它用 box1 而不是值 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)

【问题讨论】:

  • 在 Python 中(单引号或双引号)内的任何内容都是字符串
  • @sam2090 或三重或六重引号! """these too""" '''and these!'''
  • @AdamSmith 是的。多行字符串,以防将来的读者不知道他们叫什么

标签: python variables replace


【解决方案1】:

如果要替换为变量 box1 的值,则需要删除它周围的引号。试试:

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

引号将替换为包含的文本;而变量名不应该用引号引起来。

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • str(box1) 将给出元组的字符串表示,而不是55, 55.7
    • @PadraicCunningham - 如果不想要括号,我们可以使用str(box1).strip('()')
    【解决方案3】:

    正如@tigerhawk 和@sam 所说,如果您在引号中输入内容,则表示您在引号中输入的文字内容,因此请尝试删除“框 1”周围的引号

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多