【问题标题】:Trying to print with spaces instead of line changes尝试使用空格而不是换行进行打印
【发布时间】:2013-11-23 10:42:28
【问题描述】:

我刚刚发现 Python,但我找不到避免在我要打印的每个单词之间换行的方法。 我知道这一定是人们经常问的问题,这就是为什么我寻找答案,但找不到任何有效的方法。 我曾经读过它可以在我的打印命令末尾放一个逗号,但是自从发布了新版本的 Pyzo 以来,它就停止了这种工作方式。 我还阅读了有关键入 print(bla, sep=" ") 的信息,但它不起作用,所以基本上我不知道该怎么做。 这是我输入的内容:

from random import *
def vocabulaire(x):
i=1
while i<=x/2:
    print(choice(français, sep=""))
    i=i+1
while x>=i>x/2:
    print(choice(anglais,sep=""))
    i=i+1

基本上,如果我尝试执行这个程序,Pyzo 会打印:

"Traceback (most recent call last):
  File "<console>", line 1, in <module>
    from random import *
  File "C:\Users\Sébastien\Desktop\Pyzo_TD1.py", line 86, in vocabulaire
    # The full license can be found in 'license.txt'.
TypeError: choice() got an unexpected keyword argument 'sep' "

如果我只是删除“sep=""”,程序确实可以工作,但不是我想要的方式。

你知道我应该怎么做吗? (我可能在这篇文章中犯了一些语法错误,抱歉,我的英语不太流利)

Ps : "français" 和 "anglais" 是两个列表

【问题讨论】:

    标签: python spaces


    【解决方案1】:

    sepprint 的参数,而不是choice 的参数。所以,代码应该是这样的

    print(choice(français), sep=" ")
    ...
    print(choice(anglais), sep=" ")
    

    如果你真的想在一行中打印它们,你应该使用end参数,而不是sep参数,像这样

    print(choice(français), end=" ")
    ...
    print(choice(anglais), end=" ")
    

    【讨论】:

    • 感谢您这么快回答 :) 无论如何,它仍然无法正常工作,即使在此更改之后
    • 不,该程序的工作方式与没有 sep=" " 的情况相同
    • @user3024631 在他们的网站上没有说,但很好奇:import sys; print(sys.version) 向您展示了...
    • @user3024631 你的程序在引号之间真的有空格吗?
    • 我怀疑不是 sep='' 是必需的,而是提到了尾随逗号,所以我猜是 end='' (或其他)是必需的
    【解决方案2】:

    如果你不想换行,只需添加','即:

    print "aaa",
    print "bbb"
    

    【讨论】:

      【解决方案3】:

      也许这就是你想要的:

      import random
      
      def vocabulaire(x, list_one, list_two):
          i = 1
          while i <= x/2:
              print random.choice(list_one),
              i += 1
          while x >= i > x/2:
              print random.choice(list_two),
              i += 1
      

      如果你不确定如何使用一个函数,例如random.choice,你可以使用ipython来获得一些帮助。例如,在 shell 中,键入

      $ ipython
      

      然后,在 ipython 中,键入以下语句:

      import random
      help(random.choice)
      

      希望他们能提供帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-27
        • 2023-03-26
        • 1970-01-01
        • 2010-11-07
        • 2018-12-19
        • 2021-09-02
        • 2013-08-13
        相关资源
        最近更新 更多