As @Matt_G mentioned, you can replace characters in a string with str.replace(old, new)
. This method is available in python 2.7 and 3.x.
To cite the documentation for str.replace(old, new, [count])
: 'Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.' This means you can use str.replace
for replacing the substring \x00
, aka NUL, in your string with this method.
Since you wanted a solution for a returned value, see below:
def work():
return "Foo \0"
result = work()
print(result) # -> 'Foo NUL'
print(result.replace('\0', 'Bar')) # -> 'Foo Bar'
Another example with the code from your answer (Example is for python 2, since unicode
method was used):
for part_entry in part_list:
partStr = unicode(part_entry[5]).replace('\0', '')
partStr.rstrip(' \t\r\n\0')
logging.debug('******')
logging.debug('PartName= ' + partStr)
To directly remove NUL, alias \0
or \00
, line-by-line, please see the answer from Matt_G.
If you want to remove multiple characters at once (guessing based on the usage of str.rstrip
), please use str.translate
(docs: 2.7 | 3.9) instead (also for python 2 | See this SO post for the usage of translate for unicode strings):
for part_entry in part_list:
partStr = unicode(part_entry[5]).translate({
ord('\t'): None,
ord('\r'): None,
ord('\n'): None,
ord('\0'): None
})
logging.debug('******')
logging.debug('PartName= ' + partStr)
I hope this helped you and if they're any open questions feel free to ask right away.
PS: Learn more about the NUL character