【问题标题】:When to use triple single quotes instead of triple double quotes何时使用三重单引号而不是三重双引号
【发布时间】:2011-12-08 15:30:03
【问题描述】:

艰难地学习 Python,练习 10.2:

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""

print tabby_cat
print persian_cat
print backslash_cat
print fat_cat

2:改用'''(三单引号)。你能明白为什么你可以使用它而不是"""吗?

我不明白为什么我可以使用''' 而不是"""。它给了我相同的输出。有人能解释一下为什么我会使用三单引号而不是三双引号吗?它们有什么区别?

【问题讨论】:

  • 另外你不必记住python中"'之间的区别
  • 你知道为什么你可以使用' 而不是" 或者反之亦然吗?尝试应用相同的逻辑。

标签: python quotes


【解决方案1】:

您可能需要""" 而不是'''(反之亦然)的唯一原因是字符串本身是否包含三引号。

s1 = '''This string contains """ so use triple-single-quotes.'''
s2 = """This string contains ''' so use triple-double-quotes."""

如果一个字符串同时包含三单引号三双引号,那么您将不得不转义其中一个,但这种情况极为罕见。

【讨论】:

  • 非常感谢您的解释!
【解决方案2】:

我发现类似的情况需要'''而不是""",即当双引号符号出现在字符串末尾时,反之亦然。

无效语法:

print("""2 feet 4 inches can be written in 2' 4"""")
print('''2 feet can be written in 2'''')

有效语法:

print('''2 feet 4 inches can be written in 2' 4"''')
print("""2 feet can be written in 2'""")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2011-05-18
    • 2012-10-16
    • 2016-06-20
    • 2010-12-02
    • 1970-01-01
    • 2012-10-16
    相关资源
    最近更新 更多