trivicious
trivicious

Reputation: 456

How to remove carriage return characters from string as if it was printed?

I would like to remove all occurrences of \r from a string as if it was printed via print() and store the result in another variable.

Example:

>>> s = "hello\rworld"
>>> print(s)
world

In this example, how do I "print" s to a new variable which then contains the string "world"?

Background: I am using the subprocess module to capture the stdout which contains a lot of \r characters. In order to effectively analyze the string I would like to only have the resulting output.

Upvotes: 4

Views: 578

Answers (3)

mozway
mozway

Reputation: 260640

Using a regex:

import re

s = "hello\rworld"
out = re.sub(r'([^\r]+)\r([^\r\n]+)',
             lambda m: m.group(2)+m.group(1)[len(m.group(2)):],
             s)

Output: 'world'

More complex example:

import re

s = "hello\r..\nworld"

out = re.sub(r'([^\r]+)\r([^\r\n]+)',
             lambda m: m.group(2)+m.group(1)[len(m.group(2)):],
             s)

Output:

..llo
world

Upvotes: 1

Patrik Gustavsson
Patrik Gustavsson

Reputation: 87

You could use regex:

import re
s = "Example\n of\r text \r\nwith \\r!"
s2 = re.sub("\r\n", "\n", s)
s2 = re.sub("[^\n]*\r", "", s2)
print(s)
print(s2)

Upvotes: 0

burnedikt
burnedikt

Reputation: 1007

I guess one very simple way to get the same result would be to split the string on every occurrence of the carriage return (\r) and then return only the last result.

>>> s = "hello\rworld"
>>> res = s.split("\r")[-1]
>>> res
'world'

Upvotes: 0

Related Questions