[python] cmd에서 줄바꿈 없이 글자 바꾸기

2023. 6. 20. 22:01IT 인터넷/파이썬

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를 초과분 만큼만 지워버리고 새로 적기 때문에 섞이지 않습니다.

반응형