【问题标题】:How to print strings in a for loop without space in one line如何在for循环中打印字符串,一行中没有空格
【发布时间】:2016-03-27 19:44:21
【问题描述】:

我想知道如何在 for 循环中在一行中打印一些字符串,而彼此之间没有空格。

我知道在一行中连接没有空格的字符串,但在 for 循环之外:

>>> print('hi'+'hi'+'hi')
hihihi

但是,我不知道如何在 for 循环中执行此操作。

【问题讨论】:

    标签: python string for-loop


    【解决方案1】:
    s = ""
    for i in range(3):
        s += 'Hi'
    print(s)
    

    【讨论】:

      【解决方案2】:

      你可以跳过print直接调用stdout来实现:

      import sys
      for i in range(3):
          sys.stdout.write("Hi")
      sys.stdout.write("\n")
      

      输出结果为HiHiHi。有关printstdout 之间差异的详细讨论,另请参阅this question

      【讨论】:

        【解决方案3】:

        您可以使用 Python 3 中的 print 函数并像这样指定 end 字符串:

        # this import is only necessary if you are using Python 2
        from __future__ import print_function
        
        for i in range(3):
            print('hi', end='')
        print()
        

        或者,sys.stdout.write 默认情况下添加换行符。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-25
          • 2021-11-19
          • 1970-01-01
          相关资源
          最近更新 更多