gpt4 book ai didi

python - 在 Python 中替换 '\x..' 文字字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:59 24 4
gpt4 key购买 nike

我有包含“\x..”字符的目录,例如“\x00”:

#ls
c\x00mb

我想在没有这些的情况下重命名它们,因为当我将这些文件复制到 Windows 时,它们变得无法使用。所以我的 python 脚本通过这些目录并通过以下方式检测有问题的字符:

if '\\x' in dir: # dir is the name of the current directory

首先我认为我可以通过在 python 中使用 re 模块来摆脱这个问题:

new_dir_name = re.sub('\x00', r'', dir) # I am using \x00 as an example

但这没有用。有什么方法可以使用 python 替换这些字符吗?

编辑:为了理解 char,当我将 ls 通过管道传输到 xxd 时,'\' 字符出现在 ascii 表示中。在十六进制中它显示'5c'

最佳答案

string.replace为我工作:

dir = r'foo\x00bar'
print dir
dir.replace(r'\x00', '')
print dir

输出是:

foo\x00bar
foobar

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

正则表达式也适用于一般情况,但您必须对反斜杠进行转义,这样 \x 本身就不会被解释为正则表达式转义。

对于删除后跟两个十六进制数字的 \x 的一般情况:

import re
dir = r'foo\x1Dbar'
print dir
re.sub(r'\\x[0-9A-F]{2}', '', dir)
print dir

输出是:

foo\x1Dbar
foobar

关于python - 在 Python 中替换 '\x..' 文字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42443598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com