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

浪尽此生 提交于 2020-12-04 05:16:29

问题


I am wondering how can I print some strings in a for loop in one line without space between each other.

I know concatenating strings without space in one line, but outside of a for loop:

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

However, I have no idea how to do that in a for loop.


回答1:


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



回答2:


You can achieve that by skipping print and calling directly stdout:

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

Output result is HiHiHi. See also this question for a lengthy discussion of the differences between print and stdout.




回答3:


You can use the print function from Python 3 and specify an end string like this:

# 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.



来源:https://stackoverflow.com/questions/34400677/how-to-print-strings-in-a-for-loop-without-space-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!