字符串
在 Python 中创建字符串对象非常容易。只要将所需的文本放入一对引号中,就完成了一个新字符串的创建(参见清单 1)。如果稍加思考的话,您可能会感到有些困惑。毕竟,有两类可以使用的引号:单引号 (') 和双引号 (")。幸运的是,Python 再一次使这种问题迎刃而解。您可以使用任意一类引号来表示 Python 中的字符串,只要引号一致就行。如果字符串是以单引号开始,那么必须以单引号结束,反之亦然。如果不遵循这一规则,则会出现 SyntaxError 异常。
清单 1. 在 Python 中创建字符串
>>> sr="Discover Python"
>>> type(sr)
<type 'str'>
>>> sr='Discover Python'
>>> type(sr)
<type 'str'>
>>> sr="Discover Python: It's Wonderful!"
>>> sr='Discover Python"
File "<stdin>", line 1
sr='Discover Python"
^
SyntaxError: EOL while scanning single-quoted string
>>> sr="Discover Python: \
... It's Wonderful!"
>>> print sr
Discover Python: It's Wonderful!
</div>
从清单 1 中可以看出,除了字符串用适当的引号括起来之外,另外还有两个重要方面。第一,在创建字符串时,您可以混合使用单引号和双引号,只要字符串在开始位置和结束位置使用同一类型的引号。这种灵活性允许 Python 容易地保留常规的文本数据,这些常规的文本数据可能需要使用单引号来表示简写的动词形式或所属关系,以及使用双引号来表示引述文本。
第二,如果字符串用一行表示太长,您可以使用 Python 连续字符:反斜线 (\) 来对字符串进行折行。从内部机制看,在创建字符串时换行符会被忽略,在打印字符串时可以看出这一点。您可以结合使用这两个功能,来创建包含较长段落的字符串,如清单 2 所示。
清单 2. 创建长字符串
>>> passage = 'When using the Python programming language, one must proceed \ ... with caution. This is because Python is so easy to use and can be so \ ... much fun. Failure to follow this warning may lead to shouts of \ ... "WooHoo" or "Yowza".' >>> print passage When using the Python programming language, one must proceed with caution. This is because Python is so easy to use, and can be so much fun. Failure to follow this warning may lead to shouts of "WooHoo" or "Yowza".</div>
编者注:上面的示例已折行处理,这样使页面布局更合理。事实上,它本来显示为一个较长的行。
注意,当打印 passage 字符串时,所有格式将被删除,只保留一个非常 长的字符串。通常,您可以使用控制符来表示字符串中的简单格式。例如,要表示一个新行开始,您可以使用换行控制符 (\n);要表示插入一个制表符(预设空格数),可以使用制表符控制符 (\t),如清单 3 所示。
清单 3. 在字符串中使用控制符
>>> passage='\tWhen using the Python programming language, one must proceed\n\
... \twith caution. This is because Python is so easy to use, and\n\
... \tcan be so much fun. Failure to follow this warning may lead\n\
... \tto shouts of "WooHoo" or "Yowza".'
>>> print passage
When using the Python programming language, one must proceed
with caution. This is because Python is so easy to use, and
can be so much fun. Failure to follow this warning may lead
to shouts of "WooHoo" or "Yowza".
>>> passage=r'\tWhen using the Python programming language, one must proceed\n\
... \twith caution. This is because Python is so easy to use, and\n\
... \tcan be so much fun. Failure to follow this warning may lead\n\
... \tto shouts of "WooHoo" or "Yowza".'
>>> print passage
\tWhen using the Python programming language, one must proceed\n\
\twith caution. This is because Python is so easy to use, and\n\
\tcan be so much fun. Failure to follow this warning may lead\n\
\tto shouts of "WooHoo" or "Yowza".
</div>
清单 3 中的第一段按照您预期的方式使用了控制符。该段已具备良好的格式,阅读非常方便。第二个示例虽然也进行了格式化处理,但它引用的是所谓的原始字符串,即没有应用控制符的字符串。您始终可以认出原始字符串,因为该字符串的起始引号的前面有一个 r 字符,它是 raw 的缩写。
我不了解您讲的有什么可取之处,虽然这种方法可行,但创建一个段落字符串似乎非常因难。当然一定有更好的方法。与往常一样,Python 提供了一种非常简单的方法用于创建长字符串,该方法可保留创建字符串时所使用的格式。这种方法是使用三个双引号(或三个单引号)来开始和结束长字符串。在该字符串中,您可以使用任意多的单引号和双引号(参见清单 4)。
清单 4. 使用三个引号的字符串
>>> passage = """
... When using the Python programming language, one must proceed
... with caution. This is because Python is so easy to use, and
... can be so much fun. Failure to follow this warning may lead
... to shouts of "WooHoo" or "Yowza".
... """
>>> print passage
When using the Python programming language, one must proceed
with caution. This is because Python is so easy to use, and
can be so much fun. Failure to follow this warning may lead
to shouts of "WooHoo" or "Yowza".
</div>
将字符串作为一个对象
如果阅读了本系列前两篇文章中的任何一篇文章,那么在您的脑海中会立即浮现出这样一句话:在 Python 中,所有事物都是对象。到目前为止,我还没有涉及到关于 Python 中的字符串的对象特性的问题,但是,与往常一样,Python 中的字符串就是对象。事实上,字符串对象是 str 类的一个实例。正如您在 探索 Python,第 2 部分 中看到的,Python 解释器包括一个内置帮助工具(如清单 5 所示),它可以提供关于 str 类的信息。
清单 5. 获取关于字符串的帮助信息
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
| str
| basestring
| object
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
...
</div>
使用单引号、双引号和三引号语法创建的字符串仍然是字符串对象。但是您也可以使用 str 类构造函数显式地创建字符串对象,如清单 6 所示。该构造函数可以接受简单的内置数值类型或字符数据作为参数。两种方法都可以将输入的内容更改为新的字符串对象。
清单 6. 创建字符串
>>> str("Discover python")
'Discover python'
>>> str(12345)
'12345'
>>> str(123.45)
'123.45'
>>> "Wow," + " that " + "was awesome."
'Wow, that was awesome.'
>>> "Wow,"" that ""was Awesome"
'Wow, that was Awesome'
>>> "Wow! "*5
'Wow! Wow! Wow! Wow! Wow! '
>>> sr = str("Hello ")
>>> id(sr)
5560608
>>> sr += "World"
>>> sr
'Hello World'
>>> id(sr)
3708752
</div>
清单 6 中的例子也展示了关于 Python 字符串的几个其他重要方面。第一,通过将其他字符串添加在一起,可以创建新的字符串,具体方法可以使用 + 运算符,或者干脆使用适当的引号将字符串连在一起。第二,如果需要重复短字符串来创建长字符串,可以使用 * 运算符,将字符串重复一定的次数。我在本文开头说过,在 Python 中,字符串是不变的字符序列, 上例中的最后几行说明了这一点,我首先创建一个字符串,然后通过添加其他字符串对它进行修改。从对 id 方法两次调用的输出中可以看出,创建的新字符串对象中保存的是向原字符串中添加文本的结果。
str 类包含大量的用于操作字符串的有用方法。这里不做一一介绍,您可以使用帮助解释器获得有关信息。现在让我们了解一下四个有用的函数,并演示其他 str 类方法的工具。清单 7 演示了 upper、lower、split 和 join 方法。
清单 7. 字符串方法
>>> sr = "Discover Python!"
>>> sr.upper()
'DISCOVER PYTHON!'
>>> sr.lower()
'discover python!'
>>> sr = "This is a test!"
>>> sr.split()
['This', 'is', 'a', 'test!']
>>> sr = '0:1:2:3:4:5:6:7:8:9'
>>> sr.split(':')
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>

