Think Python, Chapter 8: Strings 笔记

来源:互联网 发布:淘宝直播需要什么设备 编辑:程序博客网 时间:2024/06/08 20:27

目录

这是麻省理工大学(MIT)官方编程教程中Python Tutorial的内容,教材为《Think Python: How to Think Like a Computer Scientist》。这是我的学习笔记,因为水品有限,请大家多多包涵。如果有一起学习的同学可以一起交流。如笔记中错误,请一定要告诉我啊,我肯定及时改正。所有笔记的目录详见:MIT:Python Tutorial目录

这是MIT官方编程教程中Python TutorialLoops and List Comprehensions的内容。本篇博客为《 Think Python: How to Think Like a Computer Scientist》(Think Python, Chapter 8: Strings

Python Tutorial:Loops and List Comprehensions

Before starting these problems, please read:

  • Think Python, Chapter 8: Strings
  • Think Python, Chapter 10: Lists
  • Think Python, Chapter 11: Dictionaries
  • Think Python, Chapter 12: Tuples
  • 6.01 Python Notes, Section 4: Lists (PDF)
  • 6.01 Python Notes, Section 5: Functional Style (PDF)

Chapter 8 Strings

8.1 A string is a sequence(字符串是一个序列)

object: Something a variable can refer to. For now, you can use “object” and “value” interchangeably.
sequence: An ordered set; that is, a set of values where each value is identified by an integer index.
A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

#字符串是一个字母的序列,其中,第一个字符的位置是0,不是1.>>> fruit='apple'>>> letter=fruit[1]>>> print(letter)p>>> letter=fruit[0]>>> print(letter)a

8.2 len(字符串的长度函数)

len is a built-in function that returns the number of characters in a string:

#len的长度不是从开始数的,故len(string)=string中最后一个字符的序列+1>>> len(fruit)5>>> last=fruit[len(fruit)-1]>>> print(last)e>>> 

Alternatively, you can use negative indices, which count backward from the end of thestring. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.

#但是当string[n]中n是负数的时候,则数列取得是倒数第几个(注意,这里不是从0开始的)>>> fruit[-2]#倒数第二个'l'>>> fruit[-1]#倒数第一个'e'

8.3 Traversal with a for loop

traversal(遍历): One way to write a traversal is with a while loop.

#8.3 traversal with while loopdef traversal_while(s):    index=0    while index<len(s):        letter=fruit[index]        print(letter)        index=index+1#测试>>> fruit='apple'>>> traversal_while(fruit)apple>>> 

index: An integer value used to select an item in a sequence, such as a character in a string.
Another way to write a traversal is with a for loop:

#8.3 traversal with for loopdef traversal_for(s):    for char in fruit:#这里的char是取值的变量,应该是python自带的定义        print(char)>>> fruit='apple'>>> traversal_for(fruit)apple

8.4 String slices(字符串部分)

slice: A part of a string specified by a range of indices.

#string[M:N]代表取string中Mth到Nth的字符串片段.#特别注意:开始从string[M]开始,一直取到string[N-1]>>> s='THINK PYTHON'>>> print(s[0:4])THIN>>> print(s[0:5])THINK>>> print(s[5:]) PYTHON>>> print(s[:5])THINK>>> print(s[5:5])''>>> print(s[:])THINK PYTHON

empty string: A string with no characters and length 0, represented by two quotation marks.

8.5 Strings are immutable(不可变的)

immutable: The property of a sequence whose items cannot be assigned.

>>> greeting="Hello World">>> greeting[0]='J'TypeError: 'str' object does not support item assignment

The reason for the error is that strings are immutable, which means you can’t change anexisting string. The best you can do is create a new string that is a variation on the original(现有的字符串是不可变的,你最好是创建一个新的字符串):

>>> new_greeting='J'+greeting[1:]>>> print(new_greeting)Jello World

8.6 Searching(搜寻)

search: A pattern of traversal that stops when it finds what it is looking for.

#8.6 searchingdef search_str(word,letter):    index=0    count=0    while index<len(word):        if word[index]==letter:            print(index)            count=count+1        index=index+1    print( '已搜寻完毕')    print('在',word,'中共有',count,'个',letter)#测试>>> search_str('THINK PYTHON','T')08已搜寻完毕在 THINK PYTHON 中共有 2 个 T

8.7 Looping and counting(计数)

counter: A variable used to count something, usually initialized to zero and then incremented.

#8.7 Looping and countingdef count_str(word,letter):    index=0    count=0    while index<len(word):        if word[index]==letter:            count=count+1        index=index+1    return count

8.8 String methods(方法)

method: A function that is associated with an object and called using dot(点) notation.

>>> word='banana'#upper()函数用于小写转大写>>> new_word=word.upper()>>> print(new_word)BANANA#find()函数的使用>>> index=word.find('a')>>> print(index)1#查找字符串>>> word.find('na')2#从第N个开始查找>>> word.find('na',3)4#在某个范围内查找,注意与s[M,N]一样,截止到从s[M]到s[N-1]>>> word.find('n',3,4)-1

8.9 The in operator

用’in’来判断某字符串或者字符是否在字符串内.

>>> 'a' in 'banana'True>>> 'seed'in 'banana'False

例:寻找字符串word1和word2中共有的字母

#8.9 the in operatordef in_both(word1,word2):    for letter in word1:#遍历word1,赋值到letter        if letter in word2:#判断letter是否在word2里有            print(letter)#测试>>> in_both('think','python')thn

8.10 String comparison(字符串比较)

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:
‘Banana’>’banana’
A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.(一个统一的解决方法是在比较前将所有的string都转换成有一个形式,要么都是uppercase大写的,要么都是lowercase小写的,用upper()和lower())

8.13 Exercises

Exercise 8.10.

string[M,N,T]表示取在M-N的范围中,从string[M]开始,每T个字符(每隔T-1个字符)取第一个字符

>>> fruit='banana'>>> fruit[0:5:2]'bnn'#神奇的倒着取.注意,-1代表在倒着的第一个中取第一个,-2代表倒着每两个中取第一个>>> fruit[::-1]'ananab'>>> fruit[::-2]'aaa'
0 0
原创粉丝点击