【问题标题】:formatting string on the same line在同一行上格式化字符串
【发布时间】:2012-10-24 11:29:42
【问题描述】:

如果我有这样的程序:

   def P(x):
      # x is an integer
      print str(x) 

我想要一个输出,例如:

    >>> You chose the number: X

其中 X 是在过程 P 中打印的结果。 如何在不更改程序的情况下做到这一点?

如果我这样做:

  print 'You chose the number: '
  P(x)

我会得到的

 You chose the number: 
 X

我怎样才能让它们在同一行?

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    在第一条打印语句后添加trailing逗号,以在同一行打印下一条语句:-

    print 'You chose the number: ',
    P(x)
    

    【讨论】:

      【解决方案2】:

      尝试字符串格式化:

       print 'You chose the number: {0}'.format(P(x))
      

      而不是从函数打印使用return:

         def P(x):
            return str(x) 
      

      【讨论】:

      • OP不想改变过程P(x)
      • 是的,在这种情况下,这当然是一个更好的选择,特别是当 OP 只打印传递的值的字符串表示形式时。
      【解决方案3】:

      任何一个呢

      P('You chose the number: ' + str(x))
      P('You chose the number: {0}'.format(x))
      P('You chose the number: %s' % x)
      

      ?您不必像其他答案所建议的那样更改P()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-22
        相关资源
        最近更新 更多