[Tutor] Best way to strip string string padded with nulls

Patrick K. O'Brien pobrien@orbtech.com
Wed, 6 Jun 2001 14:32:16 -0500


This is what I've come up with so far. I'm still open to suggestions.

def nullstrip(s):
    """Return a string truncated at the first null character."""
    try:
        s = s[:s.index('\x00')]
    except ValueError:  # No nulls were found, which is okay.
        pass
    return s

---
Patrick K. O'Brien
Orbtech
"I am, therefore I think."

-----Original Message-----
From: Patrick K. O'Brien [mailto:pobrien@orbtech.com]
Sent: Wednesday, June 06, 2001 1:45 PM
To: Python Tutor
Subject: RE: [Tutor] Best way to strip string string padded with nulls

Here's one problem with my solution.

null = '\x00'
c = conversation.Request("Contact1->Company")
c = c[:c.index(null)]

If there is no null in c, index returns a ValueError that would have to be
dealt with. Worse is if I used c.find(null) since find would return -1 which
would eat the last character of c. Looks like I still need to work on this.

---
Patrick K. O'Brien
Orbtech
"I am, therefore I think."