我们会学习 Python 中处理字符串的一些内置方法,这些方法可以完成下面的工作。

  • ˆˆ将字符串分解为较小的部分。
  • 将字符串联接在一起。
  • ˆˆ搜索字符串。
  • ˆˆ在字符串内搜索。
  • ˆˆ删除字符串中的某些部分。
  • 改变大小写。

字符串处理

可以用 + 号把两个字符串联接起来,就像这样:

  1. >>> print('cat' + 'dog')
  2. catdog

现在来看还可以对字符串做哪些处理。Python 中的字符串实际上都是对象,而且有自己的方法来完成搜索、分解和结合之类的操作,这些方法都称为字符串方法。

分解字符串

有时需要把一个长字符串分解成多个小字符串。通常会在字符串的某些特定位置(比如说出现某个字符的地方)进行分解。例如,在文本文件中存储数据时,常见的方法就是将各个项用逗号分隔。所以可能会得到类似这样一个名字字符串:

  1. >>> name_string = 'Sam,Brad,Alex,Cameron,TobyGwen,Jenn,Connor'

假设你想把这些名字放在一个列表中,每一项是一个名字。这就需要在出现逗号的地方分解字符串。完成这项工作的 Python 方法名为 split(),它的用法如下:

  1. >>> names = name_string.split(',')

要指出使用哪个字符作为分解标记,这个方法会返回一个列表,也就是把原来的字符串分解为许多部分。如果打印这个例子的输出,这个长长的名字串会分解为一个列表中的单个列表项:

  1. >>> print(names)
  2. ['Sam','Brad','Alex','Cameron','Toby','Gwen','Jenn','Connor']
  3. >>> for name in names:
  4. print name
  5. Sam
  6. Brad
  7. Alex
  8. Cameron
  9. Toby
  10. Gwen
  11. Jenn
  12. Connor

也可以用多个字符作为分解标记。例如,可以使用 'Toby,' 作为分解标记,这会得到下面的列表:

  1. >>> parts = name_string.split('Toby,')
  2. >>> print(parts)
  3. ['Sam,Brad,Alex,Cameron''Gwen,Jenn,Connor']
  4. >>> for part in parts:
  5. print(part)
  6. Sam,Brad,Alex,Cameron
  7. Gwen,Jenn,Connor

如果没有为 Python 指定任何分解标记,它会按空白符(whit-espace)分解字符串:

  1. >>> names = name_string.split()

空白符表示所有空格、制表符或换行符。

联接字符串

怎样把两个或多个字符串联接起来构成一个较长的字符串呢?可以使用 + 操作符把字符串联接起来。这就像把两个字符串相加,只不过这称为拼接(concatenating)。

联接字符串还有一种方法。可以使用 join() 函数。你要指出你希望把哪些字符串联接起来,另外希望在联接的各部分之间插入什么字符(如果有的话)。这实际上与 split() 正相反。下面是一个例子:

  1. >>> word_list = ['My''name''is''Warren']
  2. >>> long_string = ' '.join(word_list)
  3. >>> long_string
  4. My name is Warren

在这里,我们希望每个词之间有一个空格,所以使用了 ' '.join()

  1. >>> long_string = ' WOOF WOOF '.join(word_list)
  2. >>> long_string
  3. 'My WOOF WOOF name WOOF WOOF is WOOF WOOF Warren'

换句话说,join() 前面的字符串可以用作粘合剂,把其他字符串联接在一起。

搜索字符串

假设食谱中的各行都被放在一个列表中,每一行在列表中都是单独的元素。怎么找到“Instructions”(做法)部分呢?Python 提供了两种有用的方法:

Chocolate Cake Ingredients: 2 eggs 1/2 cup flour 1 tsp baking soda 1 lb chocolate

Instructions : Preheat oven to 350F Mix all ingredients together Bake for 30 minutes

  1. >>> name = "Frankenstein"
  2. >>> name.startswith('F')
  3. True
  4. >>> name.startswith("Frank")
  5. True
  6. >>> name.startswith("Flop")
  7. False
  8. >>> if name.startswith( "Frank"):
  9. print("Can I call you Frank?”)

还有一个类似的方法,名为 endswith()

  1. >>> name = "Frankenstein"
  2. >>> name.endswith('n')
  3. True
  4. >>>name.endwith('stein')
  5. True
  6. >>>name.endwith('stone')
  7. False

回到刚刚的问题…..如果想找到食谱的 Instructions 部分从哪里开始,可以这样做:

  1. i = 0
  2. while not lines[i].startswith ("Instructions"):
  3. i = i + 1

这个代码会一直循环,直到找到以 Instructions 开头的一行。ines[i] 表示 ilines 的索引。所以要从lines[0] (第1行)开始,然后是 lines[1] (第2行),依此类推。while 循环结束时,i 会等于“Instructions”开头的那一行的索引,这正是要找的位置。

in 和 index()

如果想在一个字符串中间找某个内容呢?可以这样做:

  1. >>> addr1 = '657 Maple Lane'
  2. >>> if 'Maple' in addr1:
  3. print("That address has 'Maple' in it.")

in 关键字只能指出子串是不是位于你检查的字符串中的某个位置,但没有告诉你它到底在什么位置。要得到这个位置,需要使用 index() 方法。类似于搜索列表,index() 会指出较小串从较大字符串中的哪个位置开始。

  1. >>> addr1 = '657 Maple Lane'
  2. >>> if 'Maple' in addr1 :
  3. position = addr1.index('Maple')
  4. print("found 'Maple' at index %i" % position)
  5. found 'Maple' at index 4

单词 Maple 从字符串 657 Maple Lane 的位置 4 开始。与列表一样,字符串中字母的索引(或位置)都是从0开始,所以M位于索引4。
image.png
注:使用 index() 之前,我们首先用 in 查看子串 Maple 是不是确实在较大的字符串中。这是因为,如果使用了index(), 而你查找的内容不在字符串中,就会得到一条错误消息。先用 in 检查可以杜绝这样的错误。

删除字部分符串

你可能常常希望删除或剥除字符串的某一部分。Python 提供了一个字符串方法 strip()

  1. >>> name = 'Warren Sande'
  2. >>> short_name = name.strip('de')
  3. >>> short name
  4. 'Warren San‘

在这里剥除了名字末尾的 de。如果末尾根本没有 de,那么什么也不会剥除:

  1. >>> name = 'Bart Simpson'
  2. >>> short_name = name.strip('de')
  3. >>> short_name
  4. 'Bart Simpson'

如果没有告诉 strip() 要剥除哪一部分,它就会去除所有空白符,包括空格、制表符和换行符。strip() 会删除字符串末尾的所有空白符。

  1. >>> name = 'Warren Sande '
  2. >>> short_name = name.strip()
  3. >>> short_name
  4. 'Warren Sande'

改变大小写

Python 提供了两个字符串方法,可以把字符串从大写转换为小写,或者反过来,从小写转换为大写。

  1. >>> string1 = "Hello"
  2. >>> string2 = string1.lower()
  3. >>> print(string2)
  4. hello
  5. >>> string3 = string1.upper()
  6. >>> print(string3)
  7. HELLO

Revision

  • 如何用 split() 分解字符串和用 join() 联接字符串。
  • 如何使用 startswith(), endswith()
  • 如何使用 inindex()
  • 如何用 strip() 去除字符串末尾的部分。
  • 如何用 upper()lower() 将字符串转换为全大写或全小写。

测试题