Python中的"字符串"和"字符串"之间有什么区别吗?

时间:2020-03-06 14:49:28  来源:igfitidea点击:

在PHP中,将解析包含在"双引号"中的字符串以替换变量,而不会解析包含在"单引号"中的字符串。在Python中,这是否也适用?

解决方案

不:

2.4.1. String and Bytes literals
  
  ...In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character...

我们可以通过3种方式在python中qoute字符串:
"细绳"
'细绳'
""
细绳
细绳
""
它们都产生相同的结果。

Python是'和'具有相同功能的少数(?)语言之一。对我来说,选择通常取决于内部内容。如果我要引用其中包含单引号的字符串,则将使用双引号。反之亦然,以减少必须转义字符串中的字符的麻烦。

例子:

"this doesn't require escaping the single quote"
'she said "quoting is easy in python"'

这记录在python文档的"字符串文字"页面上:

  • http://docs.python.org/2/reference/lexical_analysis.html#string-literals(2.x)
  • http://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals(3.x)

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中的单引号和双引号字符串是相同的。唯一的区别是单引号字符串可以包含未转义的双引号字符,反之亦然。例如:

'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'

在其他一些语言中,如果使用单引号,则不会解释元字符。以Ruby为例:

irb(main):001:0> puts "string1\nstring2"
string1
string2
=> nil
irb(main):002:0> puts 'string1\nstring2'
string1\nstring2
=> nil

在Python中,如果希望按字面意义使用字符串,则可以使用原始字符串(以'r'字符开头的字符串):

>>> print 'string1\nstring2'
string1
string2
>>> print r'string1\nstring2'
string1\nstring2