【问题标题】:How to print 2 items on the same line [duplicate]如何在同一行打印2个项目[重复]
【发布时间】:2014-08-19 03:06:54
【问题描述】:

我希望打印 new balance 的 2 行位于同一行,而不是 2 个单独的行。我该怎么做?

def main():

    # Initial balance
    balance = input ('Wallet balance: ')

    # Withdraw amount from wallet balance
    withdraw = input ('Withdraw amount: ')

    # Withdraw process and new balance display
    if withdraw > 0:
        new = balance - withdraw
        print ('Your new balance: ')
        print new

main()

【问题讨论】:

  • 你要完成的任务很简单,如上所述通过使用',' x = "123" y = "456" print x,y 问题通常是当你使用一个循环,在它里面你想使用打印。然后为了在一行中获得输出,您可以执行以下操作: import sys for i in "123456": sys.stdout.write(i) 并在一行中得到它。

标签: python formatting output python-2.x


【解决方案1】:

用逗号分隔值:

print 'Your new balance:', new

请看下面的演示:

>>> new = 123
>>> print 'Your new balance:', new
Your new balance: 123
>>>
>>> print 'a', 'b', 'c', 'd'
a b c d
>>>

请注意,这样做会自动在值之间放置一个空格。

【讨论】:

  • 妈的,比我快8秒!
  • 哇,这个网站的帮助真快,谢谢!还有一个简单的问题,我的代码中是否需要括号?
  • @TollyBear - 不在 Python 2.x 中,其中print is a statement。不过,您在 Python 3.x 中需要它们,因为 print is a function.
  • 我怎样才能让用户根据需要无限重复?
  • @iCodez 不抱歉,我不清楚,我的意思是他们可以从'#从钱包余额中提取金额提取=输入('提取金额:')#提取过程和新的如果提款> 0,余额显示:新=余额-提款打印('您的新余额:'),新的'
猜你喜欢
  • 1970-01-01
  • 2017-09-24
  • 1970-01-01
  • 2022-07-20
  • 1970-01-01
  • 2013-12-13
  • 2022-08-13
  • 2013-11-30
  • 2012-08-15
相关资源
最近更新 更多