不可以:
2.4.1. 字符串和字节字符串字面量
...简单来说:这两种类型的字面量都可以用匹配的单引号 (
'
) 或双引号 ("
) 括起来。它们也可以用匹配的三个单引号或三个双引号括起来(通常称为三引号字符串)。反斜杠 (\
) 字符用于转义一些特殊含义的字符,如换行符、反斜杠本身或引号字符等...
Python是为数不多的一种语言,其中'和"具有相同的功能。 我通常的选择取决于字符串中包含什么内容。 如果我要引用一个包含单引号的字符串,我会使用双引号,反之亦然,以减少字符串中需要转义字符的数量。
示例:
"this doesn't require escaping the single quote"
'she said "quoting is easy in python"'
在一些其他语言中,如果你使用单引号,元字符将不会被解释。Ruby 语言提供了一个例子:
irb(main):001:0> puts "string1\nstring2"
string1
string2
=> nil
irb(main):002:0> puts 'string1\nstring2'
string1\nstring2
=> nil
>>> print 'string1\nstring2'
string1
string2
>>> print r'string1\nstring2'
string1\nstring2
>>> "text"
'text'
>>> 'text'
'text'
PEP8推荐一致的规则,PEP257建议文档字符串使用三个双引号。
在Python中,单引号字符串和双引号字符串是相同的。这个PEP不为此提供建议。选择一个规则并坚持。但是,当一个字符串包含单引号或双引号字符时,请使用另一个字符以避免在字符串中使用反斜杠。它可以提高可读性。
对于三引号字符串,始终使用双引号字符以与PEP 257中的docstring约定保持一致。
广泛使用的做法是优先使用双引号来表示自然语言字符串(包括插值) - 因此任何可能成为I18N候选的内容。而单引号用于技术字符串:符号、字符、路径、命令行选项、技术正则表达式等。
(例如,在为I18N准备代码时,我会运行半自动化的REGEX,快速将双引号字符串转换为使用gettext)
在Python中,单引号和双引号的字符串是相同的。唯一的区别在于单引号的字符串可以包含未转义的双引号字符,反之亦然。例如:
'a "quoted" word'
"another 'quoted' word"
另外,还有三引号字符串,允许引号字符和换行符不被转义。
您可以使用命名占位符和locals()内置函数在字符串中替换变量:
name = 'John'
lastname = 'Smith'
print 'My name is %(name)s %(lastname)s' % locals() # prints 'My name is John Smith'
在Python中,有三种方法可以引用字符串: "string" 'string' """ string string """ 它们都会产生相同的结果。
在Python中没有区别,当生成XML时,您可以真正利用它。正确的XML语法要求在属性值周围使用双引号,在许多语言中,例如Java,这会强制您在创建像这样的字符串时对其进行转义:
String HtmlInJava = "<body bgcolor=\"Pink\">"
但在Python中,您只需使用另一个引号,并确保使用匹配的结束引号,如下所示:
html_in_python = '<body bgcolor="Pink">'
很不错吧?您还可以使用三个双引号来开始和结束多行字符串,包括EOL在内,就像这样:
multiline_python_string = """
This is a multi-line Python string which contains line breaks in the
resulting string variable, so this string has a '\n' after the word
'resulting' and the first word 'word'."""
是的。 声称在Python中单引号和双引号相同的人是错误的。
否则,在以下代码中,双引号字符串将不会需要额外的4.5%时间来处理:
import time
time_single = 0
time_double = 0
for i in range(10000000):
# String Using Single Quotes
time1 = time.time()
str_single1 = 'Somewhere over the rainbow dreams come true'
str_single2 = str_single1
time2 = time.time()
time_elapsed = time2 - time1
time_single += time_elapsed
# String Using Double Quotes
time3 = time.time()
str_double1 = "Somewhere over the rainbow dreams come true"
str_double2 = str_double1
time4 = time.time()
time_elapsed = time4 - time3
time_double += time_elapsed
print 'Time using single quotes: ' + str(time_single)
print 'Time using double quotes: ' + str(time_double)
输出:
>python_quotes_test.py
Time using single quotes: 13.9079978466
Time using double quotes: 14.5360121727
所以,如果你想要快速、干净、值得尊重的代码,并且看起来似乎很懂行,请尽可能使用单引号来表示字符串。这样做还可以通过跳过Shift键来节省更少的能量。