[python] cmd에서 줄바꿈 없이 글자 바꾸기
2023. 6. 20. 22:01ㆍIT 인터넷/파이썬
300x250
end="", "\r"을 사용하면 됩니다.
import time
# Print initial content
print("Loading...", end="")
# Wait for 1 second
time.sleep(1)
# Change characters without moving to a new line
print("\rProgress: 25%", end="")
# Wait for 1 second
time.sleep(1)
# Change characters again
print("\rProgress: 50%", end="")
# Wait for 1 second
time.sleep(1)
# Change characters one more time
print("\rProgress: 100%")
# Output the final content on a new line
print("Process completed.", end='')
예시 코드를 돌려보시면 cmd에서 Progress가 새로운 라인이 아닌 현재 라인에서 계속 변하는 게 보이실 겁니다.
end=""은 print에 자동으로 붙어있는 뉴라인 \n을 없애주고 \r은 커서를 앞으로 보내 새로운 글자로 덮어쓰게 해줍니다.
따라서 만약 다음에 올 문장이 더 짧으면 두 문장이 섞여버립니다. (앞은 두번째, 뒤는 첫번째) 충분히 덮지 못하기 때문입니다.
원래 있던 문장을 모두 지우고 새로 쓰고 싶은 땐 \b를 사용합니다.
import time
# Print initial content
content = "Initial content"
print(content, end="")
# Wait for 1 second
time.sleep(1)
# Calculate new content
new_content = "Short"
if len(new_content) < len(content):
difference = len(content) - len(new_content)
delete_chars = "\b" * difference
print(delete_chars, end="")
# Print the new content
print(new_content)
# Output the final content on a new line
print("Process completed.")
이 예시에선 new_content의 길이가 content보다 짧지만 원래 있던 char를 초과분 만큼만 지워버리고 새로 적기 때문에 섞이지 않습니다.
반응형
'IT 인터넷 > 파이썬' 카테고리의 다른 글
Chat GPT가 추천하는 파이썬 팁 (0) | 2023.06.10 |
---|---|
파이썬 주석처리 (0) | 2018.06.13 |
파이썬 설치(아나콘다, Anaconda, python, pycharm download) (0) | 2018.06.12 |
작업스케줄러를 이용한 파이썬 프로그램 자동 실행 (0) | 2016.01.14 |
파이썬 메모장으로 돌리는 법 (0) | 2016.01.13 |