【问题标题】:How to print a C format in python如何在python中打印C格式
【发布时间】:2018-01-19 05:16:09
【问题描述】:

一个python新手问题:

我想在 python 中打印带有参数列表的 c 格式:

agrs = [1,2,3,"hello"]
string = "This is a test %d, %d, %d, %s"

如何使用 python 进行打印:

这是一个测试1、2、3,你好

谢谢。

【问题讨论】:

  • 我会说去看看这里的文档:docs.python.org/3.6/library/string.html 那里的所有内容都有很好的文档记录,它应该是您首先查看的地方。
  • @bouletta:我不会将其称为重复项,因为这个特定问题涉及将现有list 格式化为顺序格式项。没错,你可以盲目地做string % (agrs[0], agrs[1], agrs[2], agrs[3]),它会起作用,但你不一定明白它为什么起作用(你需要一个tuple,而list(agrs) 工作得很好。

标签: python printf string-formatting


【解决方案1】:

以下方法不需要%字符:

agrs = [1,2,3,"hello"]
print("This is a test: {:02d},{:>10d},{:05d},{:>15s}".format(agrs[0],agrs[1],agrs[2],agrs[3]))

同样可以:

agrs = [1,2,3,"hello"]
print("This is a test: {0:02d},{1:>10d},{2:05d},{3:>15s}".format(agrs[0],agrs[1],agrs[2],agrs[3]))

每个项目都由每个大括号内的“:”后面的内容格式化,每个项目对应于括号中传递的参数以进行格式化。例如传递agrs[0],格式为“02d”,相当于C语言中的%02d。

【讨论】:

    【解决方案2】:
    l = [1,2,3,"hello"]
    print("This is a test %d, %d, %d, %s"%(l[0],l[1],l[2],l[3]))
    

    希望这行得通! 干杯芽!

    【讨论】:

      【解决方案3】:

      元组:

      例子:

      print("Total score for %s is %s  " % (name, score))
      

      在你的情况下:

      print(string % tuple(agrs))
      

      或使用新式字符串格式:

      print("Total score for {} is {}".format(name, score))
      

      或者将值作为参数传递并打印会这样做:

      print("Total score for", name, "is", score)
      

      Source

      【讨论】:

      • @ShadowRanger 方法最适合我,因为 agrs 列表是参数的变量列表。 “字符串”是一种预定义格式,因此更改它只会使其更加复杂。谢谢利亚姆。
      【解决方案4】:

      使用新式格式:这些怎么样? (只是在这里体验) 文档:https://docs.python.org/3.6/library/string.html

      args = [1,2,3,"hello"]
      string = "{}, "*(len(args)-1)+"{}" # = "{}, {}, {}, {}"
      
      'This is a test {}'.format(string.format(*args)) # inception!
      

      或者这个:

      args = [1,2,3,"hello"]
      argstring = [str(i) for i in args]
      'This is a test {}'.format(', '.join(argstring))
      

      或者简单地说:

      args = [1,2,3,"hello"]
      'This is a test {}'.format(', '.join(map(str,args)))
      

      全部打印:

      这是一个测试1、2、3,你好

      【讨论】:

        【解决方案5】:

        字符串重载模运算符%,用于printf-style formatting,特殊情况tuples 用于使用多个值进行格式化,因此您只需将list 转换为tuple

        print(string % tuple(agrs))
        

        【讨论】:

        • 这对我很有效,也是最简单的方法。谢谢。
        【解决方案6】:

        查看% 运算符。它接受一个字符串和一个这样的元组:

        print "My age is %d and my favourite char is %c" % (16, '$')
        

        【讨论】:

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