Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does \r (carriage return) work in Python [duplicate]

OS: Windows 7

my understanding is that \r moves the text to the left side of the page.

however when I executed this:

carriage_return = "I will use a carriage\rreturn"

print carriage_return

I got: return use a carriage

what I was expecting was: return

like image 615
user571099 Avatar asked Sep 09 '13 06:09

user571099


4 Answers

All the characters after the \r escape sequence move to the left and overwrite exactly those number of characters present at the starting of the statement.

In your example, return is there after \r and it is 5 characters and it replaces I will which is also 5 characters (don't forget to include space :P) so it basically replaces I will and prints return use a carriage

like image 165
Shubham Meshram Avatar answered Nov 18 '22 00:11

Shubham Meshram


Just to add to this. If you want to return to the beginning and erase the contents of the line, you can do that like this:

text = "Here's a piece of text I want to overwrite" 
repl = "BALEETED!" # What we want to write
print(text, end="\r") # Write the text and return
print(f'\r{repl: <{len(text)}}')

That last line might need a bit of explaining, so I'll break it down:

f'SOMETHING {var}' is an f-string, equivalent to 'SOMETHING {}'.format('HERE'). It's available in Python 3.6+

So replacing the hard-coded values for variables, we're returning to the beginning and then writing the replacement string, followed by enough spaces to replace the original text. If you want to use the old format method which is probably more clear in this case:

print('\r{0: <{1}}'.format(repl, len(text)))

# Which becomes when extrapolated:
print('BALEETED                                  ')

For bonus points, you don't need to use spaces, you can use anything:

print('\r{0:░<{1}}'.format(repl, len(text)))

# Which becomes when extrapolated:
print('DELETED░░░░░░░░░░░░░░░░░░░░░░░░░░░░░')

Or for extra BONUS make it into a function:

from time import sleep
def overprint(text,repl, t=1, char=" "):
    print(text, end="\r")
    sleep(t) 
    print('\r{0:{1}<{2}}'.format(repl, char, len(text)))

overprint("The bomb will explode in one sec...", "BOOM!")
like image 44
Armstrongest Avatar answered Nov 17 '22 23:11

Armstrongest


Well, it appears that you did move to the left of the line. It just left the rest of the line untouched. Note that return is 6 chars, and I will is also 6.

like image 22
Snakes and Coffee Avatar answered Nov 18 '22 00:11

Snakes and Coffee


\r takes the cursor to the beginning of the line. It is the same effect as in a physical typewriter when you move your carriage to the beginning and overwrite whatever is there.

like image 13
Seeker Avatar answered Nov 17 '22 23:11

Seeker