Python 单引号和双引号有什么区别
Python使用引号来表示字符串对象。它们可以是单引号或双引号。两种方式都是正确的,并且工作方式相同;然而,当这些引号一起使用时区别就出现了。
在本文中,我们将学习单引号和双引号之间的区别。
Python中的单引号
单引号应用于包裹Python中的小而短的字符串,例如字符串文字或标识符。您必须记住,当使用单引号作为字符串的字符,并且用单引号表示字符串时,会引发错误。在这种情况下,建议使用双引号。让我们通过一个示例来理解。
示例
在下面的示例中,我们将表示多种类型的字符串:一个单词、多个单词和多个句子。
name = 'Rahul'
print(name)
channel = 'Better Data Science'
print(channel)
paragraph = 'Rahul enjoys the content on Better Data Science. Rahul is awesome. Think like Rahul.'
print(paragraph)
hybrid = 'Hello "World"!'
print(hybrid)
输出
如果我们执行上述程序,输出如下所示:
Rahul
Better Data Science
Rahul enjoys the content on Better Data Science. Rahul is awesome. Think like Rahul.
Hello "World"!
示例
让我们看下面的另一个程序;在一个字符串中使用多个单引号。
hybrid = 'Rahul's World'
print(hybrid)
输出
如下所示,该程序引发了一个语法错误−
File "/home/cg/root/96099/main.py", line 1
hybrid = 'Rahul's World'
^
SyntaxError: unterminated string literal (detected at line 1)
Python假设字符串在“Rahul”之后结束,所以任何在此之后的内容都是语法错误。在代码编辑器中,类似这样的错误很容易被识别,因为“We”之后的区域着色不同。
解决这个问题的方法有:
- 停止使用缩写(例如we are -> we’re) – 它们很不方便。
-
转义字符串 – 这是下面我们将要讨论的一个选择。
-
使用双引号。
转义字符串
转义字符串的基本目标是防止特定字符被用于计算机语言。例如,我们不希望撇号被视为引号。
示例
在Python中转义字符串字符,使用反斜杠(\)符号。
hybrid = 'Rahul's World'
print(hybrid)
输出
该程序的输出如下所示:
Rahul's World
示例
然而,在字符串中经常使用反斜杠作为字面字符,比如表示计算机的路径。让我们看看如果你尝试打印一个带有转义字符的路径会发生什么。
print('C:\Users\John')
输出
如果我们编译并运行上述程序,会引发语法错误。
C:\Users\John
C:\Users\John
可能不是你希望看到的。事实证明,有两种方法可以避免转义字符 –
- 如果你使用原始字符串,请在第一个引号前面写上‘r’。
-
使用双斜杠来有效地转义转义字符。
以下是如何执行两者的示例 –
示例
#Write r before the first quote mark if you're using a raw string
print(r'C:\Users\John')
#Use a double backslash to effectively escape the escape character
print('C:\Users\John')
输出
如果我们执行上面的程序,输出如下所示:
C:\Users\John
C:\Users\John
这两个规则适用于用单引号和双引号括起来的字符串。在本章的进一步讨论中,我们现在讨论双引号在字符串中的用法。
Python中的双引号
推荐使用双引号进行自然语言通信、字符串插值或者当你知道字符串中会有单引号时。让我们通过下面的示例更好地理解。
示例
在下面的示例中,让我们看一些使用双引号表示字符串的情况。
name = 'Rahul'
# Natural language
print("It is easy for us to get confused with the single and double quotes in Python.")
# String interpolation
print(f"{name} said he is free today.")
# No need to escape a character
print("We're going out today.")
# Quotation inside a string
print("my favourite subject is 'maths'")
输出
如果我们编译并运行上述程序,输出结果如下:
It is easy for us to get confused with the single and double quotes in Python.
Rahul said he is free today.
We're going out today.
my favourite subject is 'maths'
正如你所看到的,将引用嵌入双引号字符串中是很简单的。也没有必要像单引号那样转义字符。
示例
请记住,在由双引号括起来的字符串中,不能再次使用双引号。这将导致与单引号相同的语法问题。让我们在下面的示例中看看。
string = "He said, "I can't handle this anymore"."
print(string)
输出
上述程序的输出如下:
File "/home/cg/root/22693/main.py", line 1
string = "He said, "I can't handle this anymore"."
^
SyntaxError: unterminated string literal (detected at line 1)
示例
为了避免这种情况,你可以使用上一节的方法,但是你可以用单引号包围字符串来代替 –
string = 'He said, "I cannot handle this anymore".'
print(string)
输出
输出结果如下所示−
He said, "I cannot handle this anymore".
结论
在Python中,单引号和双引号字符串之间的差异是可以忽略的。只要遵循编程约定,您可以任选一种用于任何情况。在某些情况下,一种类型可能比另一种类型更有优势。