줄 바꿈없이 인쇄하면 ( 'a'인쇄) 공백을 인쇄합니다. 제거하는 방법은 무엇입니까?
이 코드가 있습니다 :
>>> for i in xrange(20):
... print 'a',
...
a a a a a a a a a a a a a a a a a a a a
이처럼 출력 'a'
하지 않고 ' '
싶습니다.
aaaaaaaaaaaaaaaaaaaa
가능합니까?
결과를 얻는 방법에는 여러 가지가 있습니다. 귀하의 경우에 대한 해결책을 원한다면 @Ant 언급 한 것처럼 문자열 곱셈 을 사용하십시오 . 이것은 각 문장이 동일한 문자열을 인쇄하는 경우에만 작동 합니다. 길이 문자열을 곱하는 데 사용됩니다 (예 : 작동).print
'foo' * 20
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
이 작업을 일반적으로 수행하려면 문자열을 작성한 다음 한 번 인쇄하십시오. 이것은 문자열에 약간의 메모리를 소비하지만에 대해 한 번만 호출합니다 print
. 문자열 연결을 사용 +=
하면 연결하려는 문자열의 크기가 선형이므로 이제 빠릅니다.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
또는 sys.stdout을 사용하여 더 직접 할 수 있습니다 . 쓰기 () , print
래퍼 주위. 이것은 당신이 제공 한 원시 문자열 만 서식없이 작성합니다. 20 a
년대 말에도 줄 바꿈이 인쇄되지 않습니다 .
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
Python 3은 print
명령문을 print () 함수 로 변경하여 end
매개 변수 를 설정할 수 있습니다 . 에서 가져 오기하여> = 2.6에서 사용할 수 있습니다 __future__
. 그러나 3.x를 사용한 적이없는 사람들에게는 약간 혼란 스러울 것이므로 심각한 2.x 코드에서는 이것을 피할 것입니다. 그러나 3.x의 장점을 맛볼 수 있습니다.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
PEP 3105 부터 : Python 2.6의 새로운 기능 문서 에서 함수 로 인쇄 :
>>> from __future__ import print_function
>>> print('a', end='')
분명히 파이썬 3.0 이상 (또는 from __future__ import print_function
시작 부분에 2.6 이상)에서만 작동합니다 . 이 print
문장은 print()
Python 3.0에서 기본적 으로 제거되어 함수 가되었습니다 .
print
명령문 사이에 빈 문자열을 stdout으로 인쇄하여 공간을 억제 할 수 있습니다 .
>>> import sys
>>> for i in range(20):
... print 'a',
... sys.stdout.write('')
...
aaaaaaaaaaaaaaaaaaaa
그러나 더 확실한 해결책은 먼저 인쇄하려는 전체 문자열을 print
작성한 다음 단일 명령문으로 출력하는 것입니다 .
백 스페이스 문자 ( '\b'
)를 인쇄 할 수 있습니다 .
for i in xrange(20):
print '\ba',
결과:
aaaaaaaaaaaaaaaaaaaa
파이썬 3.x :
for i in range(20):
print('a', end='')
파이썬 2.6 또는 2.7 :
from __future__ import print_function
for i in xrange(20):
print('a', end='')
한 번에 하나씩 표시하려면 다음을 수행하십시오.
import time
import sys
for i in range(20):
sys.stdout.write('a')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.flush()
루프가 실행될 때마다 문자를 쓰도록 강제해야합니다.
부수적으로 :
인쇄는 O (1)이지만 문자열을 작성한 다음 인쇄는 O (n)입니다. 여기서 n은 문자열의 총 문자 수입니다. 따라서 문자열을 작성하는 것이 "깨끗한"반면 가장 효율적인 방법은 아닙니다.
내가하는 방법은 다음과 같습니다.
from sys import stdout
printf = stdout.write
이제 매번 줄 바꿈 문자를 반환하지 않고 문자열을 출력하는 "인쇄 기능"이 있습니다.
printf("Hello,")
printf("World!")
결과는 다음과 같습니다. Hello, World!
However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.
printf(str(2) + " " + str(4))
The output will be: 2 4
Either what Ant says, or accumulate into a string, then print once:
s = '';
for i in xrange(20):
s += 'a'
print s
without what? do you mean
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
?
this is really simple
for python 3+ versions you only have to write the following codes
for i in range(20):
print('a',end='')
just convert the loop to the following codes, you don't have to worry about other things
WOW!!!
It's pretty long time ago
Now, In python 3.x it will be pretty easy
code:
for i in range(20):
print('a',end='') # here end variable will clarify what you want in
# end of the code
output:
aaaaaaaaaaaaaaaaaaaa
More about print() function
print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)
Here:
value1,value2,value3
you can print multiple values using commas
sep = '-'
3 values will be separated by '-' character
you can use any character instead of that even string like sep='@' or sep='good'
end='\n'
by default print function put '\n' charater at the end of output
but you can use any character or string by changing end variale value
like end='$' or end='.' or end='Hello'
file=sys.stdout
this is a default value, system standard output
using this argument you can create a output file stream like
print("I am a Programmer", file=open("output.txt", "w"))
by this code you will create a file named output.txt where your output I am a Programmer will be stored
flush = False
It's a default value using flush=True you can forcibly flush the stream
as simple as that
def printSleeping():
sleep = "I'm sleeping"
v = ""
for i in sleep:
v += i
system('cls')
print v
time.sleep(0.02)
'Programing' 카테고리의 다른 글
MySQL URL, 호스트, 포트 및 사용자 이름을 어떻게 알 수 있습니까? (0) | 2020.07.09 |
---|---|
앱을 게시 할 때 zip-align을 찾을 수 없습니다 (0) | 2020.07.09 |
라디오 그룹에서 라디오 버튼을 기본값으로 설정하는 방법은 무엇입니까? (0) | 2020.07.09 |
테이블에서 마지막 행을 선택하십시오. (0) | 2020.07.09 |
HttpURLConnection이 프록시를 사용하도록하려면 어떻게합니까? (0) | 2020.07.09 |