何时使用三重单引号而不是三重双引号

何时使用三重单引号而不是三重双引号

本文介绍了何时使用三重单引号而不是三重双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

艰难地学习 Python,练习 10.2:

Learn Python the hard way, exercise 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:使用 '''(三重单引号)代替.你能明白为什么你可以使用它而不是 """ 吗?

2: Use ''' (triple-single-quote) instead. Can you see why you might use that instead of """?

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

I can't see why I might use ''' instead of """. It gives me the same output. Can someone explain me why I would use triple-single-quote instead of triple-double-quote? What's the difference between them?

推荐答案

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

The only reason you might need """ instead of ''' (or vice versa) is if the string itself contains a triple quote.

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

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

If a string contains both triple-single-quotes and triple-double-quotes then you will have to escape one of them, but this is an extremely rare situation.

这篇关于何时使用三重单引号而不是三重双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 12:16