How to get rid of \r\n from a string?

83 views Asked by At

I recently had to upgrade to Jython 2.7.2. I send in a Java map instance into my python script.

Previously my python script would print out the key, value in the map as in the below format

message: Community: public

This same string now appears as

u'message': u'Community:\t\tpublic\r

I managed to get rid of the u' prefix by doing the following

encode(encoding = 'UTF-8', errors = 'strict')

But am still left with the \t\r in the string

'message': 'Community:\t\tpublic\r

and it feels very clumsy to manually remove these from the string. Is there any good utility method that would help me to preserve the pre 2.7.7 handling of strings?

2

There are 2 answers

0
Carlos Adir On

Normally the character \r comes from a windows' file and the easiest way to get rid of them is just use replace

mystring = u'asd\r'
mystring = mystring.replace("\r", "")
print(repr(mystring))

Gives the output:

u'asd'
0
Bilesh Ganguly On

Why not use the toString() method and then replace the unwanted characters?

Sample code:

import java.util.HashMap as HashMap
import re


def test_2():
    my_map = HashMap()
    inner_map = HashMap()
    inner_map.put("community", "public")
    my_map.put("message", inner_map)

    print re.sub(r"[{}]*", "", my_map.toString()).replace("=", ": ")


if __name__ == '__main__':
    test_2()

Output:

message: community: public