Wednesday, 26 April 2017

Trimming python string after certain characters



I am creating a program where I am converting bytes into a utf-16 string. However, sometimes the string will carry over because there are trailing 0's and my string will end up like: "This is my string x00\x00\x00". I want to trim the string when I reach the first \x00 or x00 which indicates trailing 0's. How do I do this in python?



My problem is not a duplicate of another question linked in comments because trim() doesn't fully work. If I have a string that is "This is my string x00\x00 hi there x00\x00" I want just "This is my string" whereas trim would return "This is my string hi there"


Answer



Use index('\x00') to get the index of the first null character and slice the string up to the index;




mystring = "This is my string\x00\x00\x00hi there\x00"
terminator = mystring.index('\x00')

print(mystring[:terminator])
# "This is my string"


You can also split() on the null characters;




print(mystring.split(sep='\x00', maxsplit=1)[0])
# "This is my string"

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...