《Think Python 2e》学习精粹(八): 字符串

《Think Python 2e》学习精粹(八): 字符串



  • 字符串:是由字符组成的 序列(sequence),它是其他值的一个有序的集合;

1、字符串是一个序列

  • 可以用括号运算符一次访问一个字符;
>>> fruit = 'banana'
>>> letter = fruit[1]
  • 括号中的表达式被称作 索引(index) ,索引指出在序列中你想要哪个字符(因此而得名),索引是从字符串起点开始的位移量F(offset),第一个字母的位移量就是0;
  • 可以使用一个包含变量名和运算符的表达式作为索引;
  • 索引值必须使用整数(包括负整数);

2、len

  • len 是一个内建函数,其返回字符串中的字符数量;
  • 取得字符串最后一个字符的方法:
    • 用 len 函数;
    >>> fruit = 'banana'
    >>> length = len(fruit)
    >>> last = fruit[length-1]
    >>> last
    'a'
    
    • 使用负索引,即从字符串的结尾往后数,索引 -1指向最后一个字母, 索引 -2指向倒数第二个字母, 依次类推;
    >>> fruit = 'banana'
    >>> last = fruit[-1]
    >>> last
    'a'
    

3、使用for循环遍历

  • 遍历(traversal):从字符串的头部开始,依次选择每个字符,对其做一些处理, 然后继续直到结束, 这种处理模式被称作遍历 ;
  • 编写遍历的方法之一是使用 while循环(下面例子为从后到前遍历);
fruit = 'banana'
index = len(fruit) - 1
while index >= 0:
    letter = fruit[index]
    print(letter,end = ' ')
    index = index - 1
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new32.py
a n a n a b
  • 编写遍历的另一种方法是使用for循环:字符串中的第一个字符被赋值给变量 letter ,循环继续,字符串中的下一个字符被赋值给变量 letter,直到没有剩余的字符了;
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
	if letter == 'O' or letter == 'Q':
		letter = letter + 'u'
	print(letter + suffix, end = ' ')
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new33.py
Jack Kack Lack Mack Nack Ouack Pack Quack

4、字符串切片

  • 字符串的一个片段被称作 切片(slice)
  • 选择一个切片的操作类似于选择一个字符;
>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'
  • [n:m]操作符返回从第n个字符到第m个字符的字符串片段,包括第一个,但是不包括最后一个,将指向两个字符之间的索引, 想象成下面的切片索引图中那样或许对理解有帮助;
    在这里插入图片描述
    • 省略第一个索引(冒号前面的值),切片起始于字符串头部,省略第二个索引,切片一直 到字符串结尾;
    • 第一个索引大于或等于第二个,结果是 空字符串(empty string)

5、字符串是不可变的

  • 字符串是不可变的(immutable) ,不能改变一个已存在的字符串;
  • 可以创建一个新的字符串,并反映出对原有字符串的需要的变化;
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'

6、搜索

  • 遍历一个序列并在找到寻找的东西时返回——被称作 搜索(search)
  • 下面的函数 find 和 [] 运算符相反, 它接受一个字符并找到该字符所在的索引,如果没有找到该字符,函数返回 -1;
def find(word, letter, i):
	index = i
	while index < len(word):
		if word[index] == letter:
			return index
		index = index + 1
	return -1
	
print(find('banana', 'a', 4))
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new34.py
5

7、循环和计数

  • 计数器(counter) 的计数算法:变量 count 初始化为0,然后每次出现想定情况时递增,当循环结束时,count 包含了想定情况出现的总次数;
def count(str, s):
	count = 0
	for letter in str:
		if letter == s:
			count = count + 1
	return count
  • 搜索法(find) 的计数方法:不再使用字符串遍历,而是使用上一节中三参数版本的 find 函数;
def find(word, letter, i):
	l = len(letter)
	index = i
	while index < len(word):
		if word[index:index+l] == letter:
			return index
		index = index + 1
	return -1
	
def count(string, str):
	count = 0
	index = 0
	l = len(str)
	while index <= len(string):
		index = find(string, str, index)
		if index == -1:
			return count
		index = index + l
		count = count + 1
		
print(count('伟大的的祖国伟大的党', '伟大'))
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new37.py
2

8、字符串方法

  • 字符串 方法调用(invocation method) 方式:字符串名.方法名(实参);
  • 字符串方法可执行多种有用操作,例如 upper 返回全部大写的字符串 ;
>>> word = 'banana'
>>> new_word = word.upper()
>>> new_word
'BANANA'
  • 字符串 find 方法可选三个实参:字母或者子字符串、起始的索引和结束的索引(并不包括);
>>> word = 'banana'
>>> index = word.find('na', 3, 5)
>>> index
-1
>>> index = word.find('na', 3, 6)
>>> index
4

9、in 运算符

  • in 运算符是一个布尔运算符,接受两个字符串,如果第一个作为子串出现在第二个中,则返回 True ;
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

10、字符串比较

  • 关系运算符也适用于字符串;
  • 可以用关系运算符 == 检查两个字符串是否相等;
>>> 'banana' == 'banana'
True
>>> 'banana' == 'bananan'
  • 其它的关系运算符对于按字母序放置单词也很有用;
>>> 'banana' > 'orange'
False
>>> 'banana' < 'orange'
True
>>> 'banana' < 'Orange'
False
  • Python解释器中所有的大写字母出现在所有小写字母之前,为严格按字母表顺序比较,须将字符串转化为标准格式(都是小写字母或都是大写字母);

11、调试

  • 使用索引遍历序列中的值时,正确地指定遍历的起始和结束点有点困难;
def is_reverse(word1, word2):
	if len(word1) != len(word2):
		return False

	i = 0
	j = len(word2)

	while j > 0:
		#print(i, j)        # 这里添加打印语句
		if word1[i] != word2[j]:
			return False
		i = i+1
		j = j-1

	return True
	
print(is_reverse('pots', 'stop'))
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new40.py
Traceback (most recent call last):
  File "D:\WorkSpace\thinkpython2e\new40.py", line 17, in <module>
    print(is_reverse('pots', 'stop'))
  File "D:\WorkSpace\thinkpython2e\new40.py", line 10, in is_reverse
    if word1[i] != word2[j]:
IndexError: string index out of range
  • 为了调试 IndexError: string index out of range 类错误,第一步是在错误出现的行之前,打印索引的值(把前面程序中打印语句前的 # 去除),能获得更多的信息,这里第一次循环打印了索引号0 4,显然索引4超出了 ‘stop’ 索引范围、指定 j 的起始值显然有误,应该为 len(word2)-1,指定正确的索引起始值后,即能解决这个问题;
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new40.py
0 4
Traceback (most recent call last):
  File "D:\WorkSpace\thinkpython2e\new40.py", line 17, in <module>
    print(is_reverse('pots', 'stop'))
  File "D:\WorkSpace\thinkpython2e\new40.py", line 10, in is_reverse
    if word1[i] != word2[j]:
IndexError: string index out of range
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new40.py
0 3
1 2
2 1
True
  • 从打印信息可以看出,循环进行了3次,并未全部比较,用画如下堆栈图的方式,在纸上运行程序时,可以看出,由 while j > 0 语句指定的索引结束点出错,改为 while j >= 0 即能获得正确结果;

在这里插入图片描述

PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new40.py
0 3
1 2
2 1
3 0
True

猜你喜欢

转载自blog.csdn.net/weixin_41217917/article/details/112916631