【问题标题】:Double newlines instead of single one双换行符而不是单个换行符
【发布时间】:2019-02-11 11:15:06
【问题描述】:

最近我在编码挑战中遇到了一个问题。任务是处理给定格式的数据并输出正确的格式。例如,假设我有 N 个字符串的数组(比如 words[]),每个字符串需要打印在一个新行中,我遵循以下方法:

for(i = 0; i < N; ++i)cout<<words[i]<<"\n"

在 C++ 中,并且

for word in words:
    print(word)

在 Python 中。假设,数组是:

words = ["apple", "mango", "banana"]

所以上面代码的正确输出一定是:

apple
mango
banana

而是得到以下输出:

apple

mango

banana

请帮我找出错误。

【问题讨论】:

  • 您能否对列表words 中的元素执行reprfor word in words:..print(repr(word)) ?
  • 如果那是实际数据并且那是实际代码,你不可能得到那个输出。
  • 代码运行正常。如果你得到双换行符,那可能是因为单词中的每个字符串都附加了一个换行符。
  • 请发布实际代码以及您要打印的实际数据。 (了解minimal reproducible example 是什么。)
  • 这是 C++ 问题还是 Python 问题?

标签: python c++ python-3.x


【解决方案1】:

我认为实施没有问题。看看以下来自 rextester.com 的结果。

Python:https://rextester.com/ZPMRZ45393

C++:https://rextester.com/CLB25868

您是否使用 linux 终端来输出字符串?你在使用 IDE 吗?检查您的设置。如果您在 IDE 中设置为在打印语句时自动创建一个新行,那么这就是您看到双行的原因。

【讨论】:

    【解决方案2】:

    我猜你的 List(array) 中每个元素的末尾已经有一个换行符。

    你可以试试下面的代码

    for word in words:
        print(word, end='')  
    

    【讨论】:

      【解决方案3】:

      你的代码没有错:

      words = ["apple", "mango", "banana"]
      for word in words:
          print(word)
      

      输出:

      apple
      mango
      banana
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-19
        相关资源
        最近更新 更多