探索Python3: 使用字符串  

在 Python 中创建字符串对象非常容易。只要将所需的文本放入一对引号中,就完成了一个新字符串的创建(参见清单 1)。如果稍加思考的话,您可能会感到有些困惑。毕竟,有两类可以使用的引号:单引号 (‘) 和双引号 (“)。幸运的是,Python 再一次使这种问题迎刃而解。您可以使用任意一类引号来表示 Python 中的字符串,只要引号一致就行。如果字符串是以单引号开始,那么必须以单引号结束,反之亦然。如果不遵循这一规则,则会出现 SyntaxError 异常。

清单 1. 在 Python 中创建字符串

  1. >>> sr=”Discover Python”
  2. >>> type(sr)
  3. <type ‘str’>
  4. >>> sr=’Discover Python’
  5. >>> type(sr)
  6. <type ‘str’>
  7. >>> sr=”Discover Python: It’s Wonderful!”
  8. >>> sr=’Discover Python”
  9. File “<stdin>”, line 1
  10. sr=’Discover Python”
  11. ^
  12. SyntaxError: EOL while scanning single-quoted string
  13. >>> sr=”Discover Python: \
  14. … It’s Wonderful!”
  15. >>> print sr
  16. Discover Python: It’s Wonderful!

复制代码

从清单 1 中可以看出,除了字符串用适当的引号括起来之外,另外还有两个重要方面。第一,在创建字符串时,您可以混合使用单引号和双引号,只要字符串在开始位置和结束位置使用同一类型的引号。这种灵活性允许 Python 容易地保留常规的文本数据,这些常规的文本数据可能需要使用单引号来表示简写的动词形式或所属关系,以及使用双引号来表示引述文本。

第二,如果字符串用一行表示太长,您可以使用 Python 连续字符:反斜线 (\) 来对字符串进行折行。从内部机制看,在创建字符串时换行符会被忽略,在打印字符串时可以看出这一点。您可以结合使用这两个功能,来创建包含较长段落的字符串,如清单 2 所示。

清单 2. 创建长字符串

  1. >>> passage = ‘When using the Python programming language, one must proceed \
  2. … with caution. This is because Python is so easy to use and can be so \
  3. … much fun. Failure to follow this warning may lead to shouts of \
  4. … “WooHoo” or “Yowza”.’
  5. >>> print passage
  6. When using the Python programming language, one must proceed with caution.
  7. This is because Python is so easy to use, and can be so much fun.
  8. Failure to follow this warning may lead to shouts of “WooHoo” or “Yowza”.

复制代码

编者注:上面的示例已折行处理,这样使页面布局更合理。事实上,它本来显示为一个较长的行。

注意,当打印 passage 字符串时,所有格式将被删除,只保留一个非常 长的字符串。通常,您可以使用控制符来表示字符串中的简单格式。例如,要表示一个新行开始,您可以使用换行控制符 (\n);要表示插入一个制表符(预设空格数),可以使用制表符控制符 (\t),如清单 3 所示。

清单 3. 在字符串中使用控制符

  1. >>> passage=’\tWhen using the Python programming language, one must proceed\n\
  2. … \twith caution. This is because Python is so easy to use, and\n\
  3. … \tcan be so much fun. Failure to follow this warning may lead\n\
  4. … \tto shouts of “WooHoo” or “Yowza”.’
  5. >>> print passage
  6. When using the Python programming language, one must proceed
  7. with caution. This is because Python is so easy to use, and
  8. can be so much fun. Failure to follow this warning may lead
  9. to shouts of “WooHoo” or “Yowza”.
  10. >>> passage=r’\tWhen using the Python programming language, one must proceed\n\
  11. … \twith caution. This is because Python is so easy to use, and\n\
  12. … \tcan be so much fun. Failure to follow this warning may lead\n\
  13. … \tto shouts of “WooHoo” or “Yowza”.’
  14. >>> print passage
  15. \tWhen using the Python programming language, one must proceed\n\
  16. \twith caution. This is because Python is so easy to use, and\n\
  17. \tcan be so much fun. Failure to follow this warning may lead\n\
  18. \tto shouts of “WooHoo” or “Yowza”.

复制代码

清单 3 中的第一段按照您预期的方式使用了控制符。该段已具备良好的格式,阅读非常方便。第二个示例虽然也进行了格式化处理,但它引用的是所谓的原始字符串,即没有应用控制符的字符串。您始终可以认出原始字符串,因为该字符串的起始引号的前面有一个 r 字符,它是 raw 的缩写。

我不了解您讲的有什么可取之处,虽然这种方法可行,但创建一个段落字符串似乎非常因难。当然一定有更好的方法。与往常一样,Python 提供了一种非常简单的方法用于创建长字符串,该方法可保留创建字符串时所使用的格式。这种方法是使用三个双引号(或三个单引号)来开始和结束长字符串。在该字符串中,您可以使用任意多的单引号和双引号(参见清单 4)。

清单 4. 使用三个引号的字符串

  1. >>> passage = “””
  2. …         When using the Python programming language, one must proceed
  3. …         with caution. This is because Python is so easy to use, and
  4. …         can be so much fun. Failure to follow this warning may lead
  5. …         to shouts of “WooHoo” or “Yowza”.
  6. … “””
  7. >>> print passage
  8. When using the Python programming language, one must proceed
  9. with caution. This is because Python is so easy to use, and
  10. can be so much fun. Failure to follow this warning may lead
  11. to shouts of “WooHoo” or “Yowza”.

复制代码

将字符串作为一个对象

如果阅读了本系列前两篇文章中的任何一篇文章,那么在您的脑海中会立即浮现出这样一句话:在 Python 中,所有事物都是对象。到目前为止,我还没有涉及到关于 Python 中的字符串的对象特性的问题,但是,与往常一样,Python 中的字符串就是对象。事实上,字符串对象是 str 类的一个实例。正如您在 探索 Python,第 2 部分 中看到的,Python 解释器包括一个内置帮助工具(如清单 5 所示),它可以提供关于 str 类的信息。

清单 5. 获取关于字符串的帮助信息

  1. >>> help(str)
  2. Help on class str in module __builtin__:
  3. class str(basestring)
  4. |  str(object) -> string
  5. |
  6. |  Return a nice string representation of the object.
  7. |  If the argument is a string, the return value is the same object.
  8. |
  9. |  Method resolution order:
  10. |      str
  11. |      basestring
  12. |      object
  13. |
  14. |  Methods defined here:
  15. |
  16. |  __add__(…)
  17. |      x.__add__(y) <==> x+y
  18. |

复制代码

使用单引号、双引号和三引号语法创建的字符串仍然是字符串对象。但是您也可以使用 str 类构造函数显式地创建字符串对象,如清单 6 所示。该构造函数可以接受简单的内置数值类型或字符数据作为参数。两种方法都可以将输入的内容更改为新的字符串对象。

清单 6. 创建字符串

  1. >>> str(“Discover python”)
  2. ‘Discover python’
  3. >>> str(12345)
  4. ‘12345’
  5. >>> str(123.45)
  6. ‘123.45’
  7. >>> “Wow,” + ” that ” + “was awesome.”
  8. ‘Wow, that was awesome.’
  9. >>> “Wow,”” that “”was Awesome”
  10. ‘Wow, that was Awesome’
  11. >>> “Wow! “*5
  12. ‘Wow! Wow! Wow! Wow! Wow! ‘
  13. >>>  sr = str(“Hello “)
  14. >>>  id(sr)
  15. 5560608
  16. >>>  sr += “World”
  17. >>>  sr
  18. ‘Hello World’
  19. >>>  id(sr)
  20. 3708752

复制代码

清单 6 中的例子也展示了关于 Python 字符串的几个其他重要方面。第一,通过将其他字符串添加在一起,可以创建新的字符串,具体方法可以使用 + 运算符,或者干脆使用适当的引号将字符串连在一起。第二,如果需要重复短字符串来创建长字符串,可以使用 * 运算符,将字符串重复一定的次数。我在本文开头说过,在 Python 中,字符串是不变的字符序列, 上例中的最后几行说明了这一点,我首先创建一个字符串,然后通过添加其他字符串对它进行修改。从对 id 方法两次调用的输出中可以看出,创建的新字符串对象中保存的是向原字符串中添加文本的结果。

str 类包含大量的用于操作字符串的有用方法。这里不做一一介绍,您可以使用帮助解释器获得有关信息。现在让我们了解一下四个有用的函数,并演示其他 str 类方法的工具。清单 7 演示了 upper、lower、split 和 join 方法。

清单 7. 字符串方法

  1. >>> sr = “Discover Python!”
  2. >>> sr.upper()
  3. ‘DISCOVER PYTHON!’
  4. >>> sr.lower()
  5. ‘discover python!’
  6. >>> sr = “This is a test!”
  7. >>> sr.split()
  8. [‘This’, ‘is’, ‘a’, ‘test!’]
  9. >>> sr = ‘0:1:2:3:4:5:6:7:8:9’
  10. >>> sr.split(‘:’)
  11. [‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’]
  12. >>> sr=”:”
  13. >>> tp = (‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’)
  14. >>> sr.join(tp)
  15. ‘0:1:2:3:4:5:6:7:8:9’

复制代码

前两个方法 upper 和 lower 很容易理解。它们只是分别将字符串都转换成大写字母或小写字母。split 方法很有用,因为它可以将一个字符串分成几个较小的字符串序列,方法是将令牌字符(或给定字符序列中的任何字符)用作断开位置的指示器。所以,第一个 split 方法示例使用默认的令牌将字符串“This is a test”拆分开,此令牌可以是任何空白字符(这个序列包括空格、制表符和换行符)。第二个 split 方法演示如何使用不同的令牌字符(本例中使用的是冒号)将一个字符串分成一系列字符串。最后的一个例子显示如何使用 join 方法,该方法的作用与 split 方法相反, 可以使多个短字符串序列形成一个长字符串。在本例中,使用冒号将 tuple 包含的由单个字符构成的字符串序列连接在一起。

将字符串用作字符的容器

在本文的开头部分,我着重强调了 Python 中的字符串是不变的字符序列。本系列的第 2 部分 探索 Python,第 2 部分 介绍了 tuple,它也是一个不变的序列。tuple 通过以下方式支持访问序列中的元素:使用索引符号,使用片段分离序列中的元素,以及使用特定的片段或将不同的片段添加在一起来创建新的元组。根据这一情况,您可能想知道是否可以将同一技巧应用于 Python 字符串。如清单 8 所示,答案显然是“可以”。

清单 8. 字符串方法

  1. >>> sr=”0123456789″
  2. >>> sr[0]
  3. ‘0’
  4. >>> sr[1] + sr[0]
  5. ’10’
  6. >>> sr[4:8]     # Give me elements four through seven, inclusive
  7. ‘4567’
  8. >>> sr[:-1]     # Give me all elements but the last one
  9. ‘012345678’
  10. >>> sr[1:12]    # Slice more than you can chew, no problem
  11. ‘123456789’
  12. >>> sr[:-20]    # Go before the start?
  13. >>> sr[12:]     # Go past the end?
  14. >>> sr[0] + sr[1:5] + sr[5:9] + sr[9]
  15. ‘0123456789’
  16. >>> sr[10]
  17. Traceback (most recent call last):
  18. File “<stdin>”, line 1, in ?
  19. IndexError: string index out of range
  20. >>> len(sr)     # Sequences have common methods, like get my length
  21. 10

复制代码

在 Python 中,将字符串作为字符序列进行处理是非常简单的。您可以获得单个元素,将不同的元素添加在一起,切出几个元素,甚至将不同的片段添加在一起。进行切片的一个非常有用的特性是,在开始之前或结束之后进行较多切片不会抛出异常,只是相应地以默认方式开始或结束该序列。相反,如果您试图使用允许范围之外的索引来访问单个元素,则会得到一个异常。这种行为说明了为什么 len 方法是如此重要。

字符串:功能强大的工具

在本文中,我介绍了 Python 字符串,它是一种不变的字符序列。在 Python 中,您可以使用多个方法很容易地创建字符串,其中包括使用单引号、双引号或更灵活的方式,即使用一组三个引号。假设 Python 中的每个事物都是一个对象,您可以使用底层的 str 类方法来获得附加功能或直接使用字符串的序列功能。

 

欢迎大佬支持本博客的发展 -- Donate --

本文链接:探索Python3: 使用字符串

转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:三十岁,谢谢!^^


分享到:          
  1. 没有评论

  1. 没有通告