简体   繁体   English

如何在 for 循环中打印一行中没有空格的字符串

[英]How to print strings in a for loop without space in one line

I am wondering how can I print some strings in a for loop in one line without space between each other.我想知道如何在一行中打印 for 循环中的一些字符串而彼此之间没有空格。

I know concatenating strings without space in one line, but outside of a for loop:我知道在一行中连接没有空格的字符串,但在 for 循环之外:

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

However, I have no idea how to do that in a for loop.但是,我不知道如何在 for 循环中执行此操作。

s = ""
for i in range(3):
    s += 'Hi'
print(s)

You can achieve that by skipping print and calling directly stdout :您可以通过跳过print并直接调用stdout来实现:

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

Output result is HiHiHi .输出结果为HiHiHi See also this question for a lengthy discussion of the differences between print and stdout .另请参阅此问题,详细讨论printstdout之间的区别。

You can use the print function from Python 3 and specify an end string like this:您可以使用 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()

Alternatively, sys.stdout.write does not add a newline character by default.或者, sys.stdout.write默认添加换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM