【问题标题】:How to perform action on a integer placeholder in python?如何在python中对整数占位符执行操作?
【发布时间】:2019-11-15 08:24:46
【问题描述】:
print('%s is (%d+10) years old' % ('Joe', 42))

输出:乔 (42+10) 岁

预期输出:Joe 52 岁

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:

    您可以在 Python 3.6+ 中使用 f-strings 来做到这一点。

    name = "Joe"
    age = 42
    print(f'{name} is {age + 10} years old')
    

    【讨论】:

      【解决方案2】:

      字符串格式化将值插入字符串。要对一个值进行操作,您应该首先计算该值,然后然后将其插入/格式化到字符串中。

      print('%s is %d years old' % ('Joe', 42 + 10)
      # or  if you really want to something like that (python 3.6+)
      name = 'joe' 
      age = 42
      f'{name} is {age +10} years old'
      

      【讨论】:

        【解决方案3】:

        你不能在字符串中进行算术运算。

        print('%s is (%d) years old' % ('Joe', 42+10))
        

        【讨论】:

          【解决方案4】:

          F-strings (PEP 498 : Python V 3.6) 可以更好地处理您的情况,因为 f-string 表达式是在运行时评估的。例如:

          name = 'Joe'
          a, b = 42, 10
          print(f'{name} is {a + b} years old')
          

          【讨论】:

            【解决方案5】:

            您在错误的字符串中添加值。

            print('%s is %d years old' % ('Joe', 42+10))
            

            【讨论】:

              【解决方案6】:

              三种方式

              print('%s is %d years old' % ('Joe', 42+10))
              print('{0} is {1} years old'.format('Joe', 42+10))
              name='Joe'
              print(f'{name} is {42+10} years old')
              

              只是其他一些打印方式

              print(name,'is',(42+10),'years old')
              print(eval("name + ' is ' + str(42+10) + ' years old'"))
              

              【讨论】:

                【解决方案7】:
                print('%s is (%d+10) years old' % ('Joe', 42)
                name='joe'
                age=42+10
                print(f'{name} is {age} years old')
                

                【讨论】:

                  【解决方案8】:

                  这里我使用 模板字符串 来使用另一种方法来执行此操作。这是一种更简单但功能更弱的机制

                  使用模板字符串的最佳时机是在您处理用户生成的格式化字符串时。由于降低了复杂性,模板字符串是更安全的选择。

                  这里是模板字符串的例子:

                  >>>from string import Template
                  >>>name = 'Joe'
                  >>>age=42
                  >>>t = Template('$name is $age years old')
                  >>>t.substitute(name = name, age=age+10)
                  

                  输出

                  '乔今年 52 岁'

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-09-21
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-09-17
                    相关资源
                    最近更新 更多