【问题标题】:How to replace backslashes to a different character in a string Python如何将反斜杠替换为字符串Python中的不同字符
【发布时间】:2022-01-15 02:38:28
【问题描述】:

我想知道如何使用 Python 的 str.replace() 函数(或类似函数)来替换反斜杠...

当我尝试这样做时:

>>> temp = r"abc\abc"
>>> temp.replace(r'\'', 'backslash')
'abc\\abc' # For some reason, temp.replace() does not replace '\' with 'backslash' even when using raw variable
>>> temp.replace(r'\\', 'backslash') # Same result
'abc\\abc'

我该如何解决这个问题?为什么? (Linux、Debian/Ubuntu、x86_x64 处理器)

【问题讨论】:

    标签: python string replace backslash


    【解决方案1】:

    你需要转义反斜杠 -

    temp = r"abc\abc"
    temp.replace('\\', 'backslash')
    'abcbackslashabc'
    

    【讨论】:

    • 这里重要的是不要使用r(原始字符串)作为单个反斜杠,因为r'\\' 是一个带有两个反斜杠的字符串。是的,这令人困惑。
    • 我明白...\\ 就像是\... 的快捷方式或别名...而r'\\' 实际上是两个反斜杠
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多