简体   繁体   English

替换字符串中的单引号和双引号

[英]replace single quotes and double quotes from a string

I am a trying to learn python and I have an issue where I encounter string that has both single and double quotes that I need to replace.我正在尝试学习 python 并且遇到了一个问题,即我遇到了需要替换单引号和双引号的字符串。 My objective would be to split them to a list but still preserve the single and double quotes for other reasons.我的目标是将它们拆分为一个列表,但由于其他原因仍保留单引号和双引号。 I tried the below but getting the errors我尝试了以下但收到错误

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

Simply use a backslash to escape the double-quotes.只需使用反斜杠来转义双引号。

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

Or use a single-quoted string and escape the single-quote.或者使用单引号字符串并转义单引号。 (This is the canonical representation.) (这是规范表示。)

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

Or use triple-quotes - single or double.或者使用三引号 - 单引号或双引号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM