首页 > 解决方案 > 替换字符串中的单引号和双引号

问题描述

我正在尝试学习 python,我遇到了一个问题,我遇到了需要替换单引号和双引号的字符串。我的目标是将它们拆分为一个列表,但由于其他原因仍保留单引号和双引号。我尝试了以下但收到错误

s=("I said, "hello" it's mine".replace(""",'`')).replace("'","^")
print(s)

File "<ipython-input-58-a5276888c42f>", line 1
    s=("I said, "hello" it's mine".replace(""",'`')).replace("'","^")
                     ^
SyntaxError: invalid syntax

标签: pythonpython-3.xstringparsing

解决方案


只需使用反斜杠来转义双引号。

s = "I said, \"hello\" it's mine"

或者使用单引号字符串并转义单引号。(这是规范表示。)

s = 'I said, "hello" it\'s mine'

或者使用三引号 - 单引号或双引号。

s = """I said, "hello" it's mine"""
s = '''I said, "hello" it's mine'''

推荐阅读