首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要类似TypeError字节的对象,而不是字符串

需要类似TypeError字节的对象,而不是字符串
EN

Stack Overflow用户
提问于 2020-08-21 00:24:51
回答 1查看 399关注 0票数 1

我必须将python 2.7脚本重新编码为python 3.8。我遇到了这种类型的错误:

name = name.replace(char,'str‘) TypeError:需要类似字节的对象,而不是’str‘

在尝试在互联网上找到解决方案后,我有点理解python3编码和解码字节和字符串的方式与Python2.7不同。然而,作为python的新手,我尝试了一些解决方案,但仍然收到这个错误。

代码语言:javascript
复制
forbidden_char = ['~', '"', '#', '%', '&', '*', ':',
                      '<', '>', '?', '/', '\\', '{', '|', '}', ',']

print("Sanitizing {} folder...".format(folder))
        for root, dirnames, filenames in os.walk(folder):

            for name in filenames + dirnames:
                original_name = name
                # original_root = root

                if force:
                    name = removeAccentsAndAll(name)
                else:
                    force_rename = False
                    # Only take UTF8 names
                    try:
                        name.decode('utf-8')
                    except:
                        print("  Found non-UTF8 name, re-encoding everything...")
                        name = name.encode('utf-8')
                        # root = root.encode('utf-8')

                # Remove trailing and ending spaces
                if name[0] == ' ':
                    print("  Trailing spaces detected, removing")
                    name = name.lstrip(' ')
                if name[-1] == ' ':
                    print("  Ending spaces detected, removing")
                    name = name.rstrip(' ')

                # Remove all ending points
                if name[-1:] == '.':
                    print("  Ending points detected, removing")
                    name = name.rstrip('.')

                # Remove forbidden char only if we are in blacklist mode
                if not force:
                    for char in forbidden_char:
                        name = name.replace(char, '_')

我猜错误来自“'_‘”,但即使我尝试将其编码为字节,它也不起作用。

有什么建议吗?

干杯,Xzi。

EN

回答 1

Stack Overflow用户

发布于 2020-08-21 02:51:40

通过在"name.replace(char,b'_')和名为"forbidden_char“的列表中添加"b”后缀,代码已修复。

Xzi。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63509330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档