如何使这个saveString更安全(python)

2024-06-16 09:11:47 发布

您现在位置:Python中文网/ 问答频道 /正文

unsafeLetters = ["\\a","\\b","\\f","\\n","\\r","\\t","\\v"]
def getSaveString(string):
    """ Strips colorcodes and newlinecharacters"""
    newstring = ""
    for x in string:
        if ord(x) > 8:
            newstring += x
    newstring = repr(newstring)
    for x in unsafeLetters:
        newstring = newstring.replace(x, "\\\\"+x)

    newstring = eval(newstring)

    return newstring

如何使这个saveString更节省色码和换行符

主要获得:

TypeError: 'int' object is not iterable
Occurrences: 2
Last occurrence: 08/21/15 00:57:07
occurrences: 1
Last occurrence: 08/20/15 13:29:57

谢谢


Tags: andinforstringifdeflastoccurrence
1条回答
网友
1楼 · 发布于 2024-06-16 09:11:47

从你的代码中你想做什么并不那么明显,因为似乎没有一个定义来定义什么是“色码”,尽管你说你想去掉它们,但事实上你似乎在试图逃避它们

作为第一步,我已经用原始字符串常量替换了字符串常量,因为这确实使事情更容易理解(不再需要将反斜杠加倍)

如果你能修改你的问题,更清楚地表达你的意图,我会尽量多帮你一点

unsafeLetters = [r"\a", r"\b", r"\f", r"\n", r"\r", r"\t", r"\v"]
def getSaveString(string):
    """ Strips colorcodes and newlinecharacters"""
    newstring = ""
    for x in string:
        if ord(x) > 8:
            newstring += x
    newstring = repr(newstring)
    for x in unsafeLetters:
        newstring = newstring.replace(x, r"\\"+x)

    newstring = eval(newstring)

    return newstring

相关问题 更多 >