【问题标题】:Adding """ at the beginning and end of a string?在字符串的开头和结尾添加“””?
【发布时间】:2011-08-21 15:58:20
【问题描述】:

每当我输入像"Muhammed went to the store and said "Can I have some pickles please"" 这样的字符串时,似乎会搞砸字符串的处理方式,因为Can I have some pickles please 变得无效。所以我认为在它的两侧添加“”肯定会解决它,如果有更好的解决方案,我愿意接受。

【问题讨论】:

  • “饲料”?这是输入数据还是源代码?如果是源代码,您可以将单引号与双引号互换使用('xxx "yyy"')或转义双引号("xxx \"yyy\"")。
  • 通过提要我的意思是输入数据。有时我会输入整个文件,所以浏览它并输入反斜杠并不是一个真正的选择
  • 字符串从何而来,如何使用?为什么不从外部文件中读取而不是放在源代码中?
  • 听起来您正在将输入数据放入源代码中。不要那样做;改用文件或标准输入。
  • @Nicholas:你应该把它放在答案而不是评论中。这是唯一正确的答案,也是唯一能得到我支持的答案。

标签: python string formatting


【解决方案1】:

你可以转义内引号:

"Muhammed went to the store and said \"Can I have some pickles please\""

或使用单引号

'Muhammed went to the store and said "Can I have some pickles please"'

【讨论】:

  • 我应该很清楚,有时字符串太大而无法转到有反斜杠的实例,还有其他方法吗?
  • @Louis93:“太大”是什么意思?结果字符串将是正确的大小,只是源代码会稍长。
  • 我的意思是我可能会输入一个包含大量语音标记和单个引号的段落。在我无法越过它并在它们附近输入反斜杠的情况下,我将如何在没有标点符号干扰的情况下将其全部更改为一串字符串?
  • @Louis93:在这种情况下,您将使用您提到的三引号语法。由于某种原因,这对您不起作用吗?
  • 好吧,假设它以语音标记结尾,那就不行了。您上面的答案也提到了这一点。
【解决方案2】:

选择一个:

'Muhammed went to the store and said "Can I have some pickles please"'
"Muhammed went to the store and said \"Can I have some pickles please\""

你不能这样修复它

"""Muhammed went to the store and said "Can I have some pickles please""""

因为这样你就可以让他在Muhammed went to the store and said "Can I have some pickles please 后面加上一个额外的"

一般你也可以使用

'''Muhammed went to the store and said "Can I have some pickles please"'''

相反,但这对您的示例毫无意义。

【讨论】:

  • 如果字符串太大而无法放置反斜杠怎么办?
【解决方案3】:

听起来您正在将输入数据放入源代码中。不要那样做;请改用文件或sys.stdin

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2014-02-18
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多