格式化同一lin上的字符串

2024-03-28 15:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下程序:

   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

我怎样才能让他们站在同一条线上?你知道吗


Tags: the程序youannumberisdef情况
3条回答

尝试设置字符串格式:

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

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

   def P(x):
      return str(x) 

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

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

你们中有谁呢

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

什么?你不必像其他答案所建议的那样改变P()。你知道吗

相关问题 更多 >