【问题标题】:Insert variable values into a string [duplicate]将变量值插入字符串[重复]
【发布时间】:2011-03-22 23:46:17
【问题描述】:

我想在 Python 中将变量 [i] 引入到字符串中。

例如看下面的脚本。我只是希望能够为图像命名,例如geo[0].tif ... to geo[i].tif,或者如果您使用会计师,因为我可以替换价值链的一部分来生成计数器。

data = self.cmd("r.out.gdal in=rdata out=geo.tif")
self.dataOutTIF.setValue("geo.tif")

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用运算符% 将字符串注入字符串:

    "first string is: %s, second one is: %s" % (str1, "geo.tif")
    

    这将给出:

    "first string is: STR1CONTENTS, second one is geo.tif"
    

    你也可以用%d做整数:

    "geo%d.tif" % 3   # geo3.tif
    

    【讨论】:

      【解决方案2】:
      data = self.cmd("r.out.gdal in=rdata out=geo{0}.tif".format(i))
      self.dataOutTIF.setValue("geo{0}.tif".format(i))
      
      str.format(*args, **kwargs)
      

      执行字符串格式化操作。 this 所在的字符串 方法被调用可以包含文字 分隔的文本或替换字段 通过大括号 {}。每个替换字段 包含 a 的数字索引 位置参数,或名称 关键字参数。返回副本 每次替换所在的字符串 字段被替换为字符串 对应参数的值。

      >>> "The sum of 1 + 2 is {0}".format(1+2)
      'The sum of 1 + 2 is 3'
      

      有关各种格式的说明,请参阅格式字符串语法 可以指定的选项 格式化字符串。

      这种字符串格式化方法是 Python 3.0 中的新标准,并且 应该优先于 % 字符串中描述的格式 新代码中的格式化操作。

      New in version 2.6.
      

      【讨论】:

      • 这些天 .format 被认为比我的解决方案更具 Python 风格?
      • 是的,它是官方认可的,而你的解决方案不是,iirc。没有责备:)
      • @orangeoctopus,仅适用于 Python2.6+ docs.python.org/library/stdtypes.html#str.format
      • 谢谢!我将开始使用它。
      【解决方案3】:

      如果您使用的是 python 3,那么您可以使用 F-string。这是一个例子

       record_variable = 'records'    
       print(f"The element '{record_variable}' is found in the received data")
      

      在这种情况下,输出将是:

      在接收到的数据中找到元素“记录”

      【讨论】:

        【解决方案4】:

        使用

        var = input("Input the variable")
        print("Your variable is " + var)
        

        注意var必须是字符串,如果不是,用var = str(var)转换成字符串。

        例如

        var = 5  # This is an integer, not a string
        print("Var is " + str(var))
        

        此解决方案最容易阅读/理解,因此更适合初学者,因为它只是简单的字符串连接。

        【讨论】:

          【解决方案5】:

          如果您使用的是 python 3.6+,最好的解决方案是使用 f-strings:

          data = self.cmd(f"r.out.gdal in=rdata out=geo{i}.tif")
          self.dataOutTIF.setValue(f"geo{i}.tif")
          

          这是更具可读性和性能的解决方案。

          【讨论】:

            【解决方案6】:

            您也可以这样做:

            name = input("what is your name?")
            print("this is",+name)
            

            【讨论】:

            • 其实这样不行..你的意思是print("this is " + name)
            猜你喜欢
            • 2018-12-04
            • 1970-01-01
            • 2020-11-21
            • 2022-11-02
            • 2017-10-22
            • 1970-01-01
            • 2017-03-18
            • 1970-01-01
            相关资源
            最近更新 更多