【问题标题】:Removing NUL in string删除字符串中的 NUL
【发布时间】:2018-07-27 21:23:56
【问题描述】:

如何去除字符串中的 NUL 字符/空格? 我试图在这里使用整个答案和 cmets。似乎它们都不适合我。

例如字符串是m o d e m

 for part_entry in part_list:
        partStr = unicode(part_entry[5])
        partStr.rstrip(' \t\r\n\0')
        logging.debug('******')
        logging.debug('PartName= '+partStr)

This is我目前正在编译的。

我尝试记录它,它的渲染输出是这样的;

【问题讨论】:

  • 太棒了!没有没有没有评论只是投票!
  • 嗯....你知道rstrip是做什么的吗?
  • 这是我最后一次尝试。左右。我现在很绝望:(
  • 嗯,中间的NUL不是左也不是右是吧?但我不确定你的评论“空白”。您自己的尝试正确 (!) 列出了 \t、\r、\n 和 \0,但忽略了空格本身。它也应该被删除吗?您不想用正确的单个空格替换这些字符吗?
  • 我的问题是space,而图像上的NUL 恰好在附加的日志图像上记录了“PartName”

标签: python python-2.7


【解决方案1】:

试试这个:

content = []
with open('file.ext', as 'r') as file_in:
    content = file_in.readlines()

new_content = [] 
for line in file:
    clean_line = line.replace('\00', '')
    new_content.append(clean_line)

with open('outfile.ext', 'w') as file_out:
    file_out.writelines(new_content)

【讨论】:

  • 我想我不能这样做,这不是来自文本文件。字符串来自结果/过程
  • @Bianca 它来自哪里无关紧要,您以相同的方式删除字符。
  • 谢谢你,Matt_G,你拯救了我的一天
【解决方案2】:

正如@Matt_G 提到的,您可以用str.replace(old, new) 替换字符串中的字符。此方法在 python 2.7 和 3.x 中可用。

引用the documentation 为str.replace(old, new, [count]):'返回字符串的副本,其中所有出现的旧子字符串都替换为新的。如果给出了可选参数计数,则仅替换第一个计数出现。这意味着您可以使用 str.replace 替换字符串中的子字符串 \x00,即 NUL。

由于您想要返回值的解决方案,请参见下文:

def work():
    return "Foo \0"

result = work()

print(result) # -> 'Foo NUL'
print(result.replace('\0', 'Bar')) # -> 'Foo Bar'

您的答案中的代码的另一个示例(示例适用于 python 2,因为使用了 unicode 方法):

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)

直接删除NUL,别名\0或\00,逐行查看,请看Matt_G的回答。

如果您想一次删除多个字符(根据str.rstrip 的用法猜测),请改用str.translate(文档:2.7 | 3.9)(也适用于 python 2 | See this SO发布 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)

我希望这对您有所帮助,如果他们有任何未解决的问题,请随时提出。

PS:Learn more about the NUL character

【讨论】:

    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 2013-03-04
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2023-02-25
    • 1970-01-01
    相关资源
    最近更新 更多