developer tip

같은 줄에 새 출력 인쇄

optionbox 2020. 8. 28. 07:22
반응형

같은 줄에 새 출력 인쇄


이 질문에 이미 답변이 있습니다.

루프 출력을 같은 줄의 화면에 인쇄하고 싶습니다.

Python 3.x에서 가장 간단한 방법으로 어떻게합니까?

이 질문은 줄 끝에 쉼표를 사용하여 Python 2.7에 대해 요청되었음을 알고 있습니다. 즉 print I이지만 Python 3.x에 대한 해결책을 찾을 수 없습니다.

i = 0 
while i <10:
     i += 1 
     ## print (i) # python 2.7 would be print i,
     print (i) # python 2.7 would be 'print i,'

화면 출력.

1
2
3
4
5
6
7
8
9
10

내가 인쇄하고 싶은 것은 :

12345678910

새로운 독자는 http://docs.python.org/release/3.0.1/whatsnew/3.0.html 이 링크를 방문합니다.


에서 help(print):

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

다음 end키워드 를 사용할 수 있습니다 .

>>> for i in range(1, 11):
...     print(i, end='')
... 
12345678910>>> 

참고가해야하는 print()마지막 개행 자신. BTW, Python 2에서 후행 쉼표와 함께 "12345678910"이 표시되지 1 2 3 4 5 6 7 8 9 10않고 대신 표시됩니다.


* Python 2.x 용 *

줄 바꿈을 피하려면 후행 쉼표를 사용하십시오.

print "Hey Guys!",
print "This is how we print on the same line."

위 코드 스 니펫의 출력은 다음과 같습니다.

Hey Guys! This is how we print on the same line.

* Python 3.x 용 *

for i in range(10):
    print(i, end="<separator>") # <separator> = \n, <space> etc.

위 코드 스 니펫의 출력은 (when <separator> = " "),

0 1 2 3 4 5 6 7 8 9

제안 된 것과 유사하게 다음을 수행 할 수 있습니다.

print(i,end=',')

출력 : 0, 1, 2, 3,


다음과 같은 작업을 수행 할 수 있습니다.

>>> print(''.join(map(str,range(1,11))))
12345678910

print("single",end=" ")
print("line")

이것은 출력을 제공합니다

single line

질문 사용을 위해

i = 0 
while i <10:
     i += 1 
     print (i,end="")

>>> for i in range(1, 11):
...     print(i, end=' ')
...     if i==len(range(1, 11)): print()
... 
1 2 3 4 5 6 7 8 9 10 
>>> 

다음 줄의 프롬프트 뒤에서 인쇄가 실행되지 않도록하는 방법입니다.


같은 줄에 0에서 n까지의 숫자를 인쇄하려는 예를 들어 보겠습니다. 다음 코드를 사용하여이를 수행 할 수 있습니다.

n=int(raw_input())
i=0
while(i<n):
    print i,
    i = i+1

입력시 n = 5

Output : 0 1 2 3 4 

참고 URL : https://stackoverflow.com/questions/12032214/print-new-output-on-same-line

반응형