《think in python》学习-8

字符串

字符串是一个序列,可以用方括号操作符来访问字符串中的单独字符

fruit = 'banana'
letter = fruit[1] 

方括号中的表达式称为下标 下标从0 开始

任何表达式,包括变量和操作符 都可以做为下标

len

len是一个内置函数,可以返回字符串的个数

friut = 'banana'
print len(friut)

使用for循环进行遍历

    index = 0 
    while index<len(fruit):
        letter = fruit[index]
        print index
        index = index+1

字符串切片

字符串中的一段称为一个切片

s = "hello world"
print s[0:5] 
hello

操作符[n:m] 返回从字符串n个字符起到第M个字符部分,包含n但是不包含m

字符串是不可变的

修改字符串 会报错,本身不可修改。你可以新建一个字符

fruit = 'hello'
furit[0]='j'  # 报错
letter = fruit[0] #√

搜索

通过便利操作,可以在一个指定的字符窜中找到我们想找的字符

def find(word,letter):
    index=0
    while index<len(word):
        if word[index]==letter:
            return index
        index= index+1
    return -1

循环和计数

通过循环,我们可以用变量每次累加的方式 统计次数

def count():
    word = 'banana'
    count =0
    for letter in word:
        if letter == 'a':
            count = count+1
    print count

字符串方法

word = 'banana'
print word.upper()  #大写

print word.find('a')  #查找

print word.find("a",3) #从下标3开始查找

print word.find("a",3,5) #从下标3开始查找 5结束

操作符in

in 是一个布尔操作符,操作于2个字符串上

 'a' in 'banana'
 True
 
 #例如
 
 def in_both(word1,word2):
    for letter in word1:
        if letter in word2:
            print letter

字符串比较

if word == 'banana'
    print True
    

字符串 比较> 或者< 时,会按照字母顺序比较,大写字母比小写字母要大。

练习

  1. 编写一个函数接受字符串为形参,倒序显示他的字母 每个字母单独一行
        def desort(c):
        index = len(c)-1
        while index>=0:
            print c[index]
            index = index-1
    
  2. 给定fruit是一个字符串,fruit[:]表示什么
    fruit = 'hello'
    print fruit[:]  #字符本身
  1. 改良find函数,让它接受第3个形参,表示word从哪个下标开始搜索
    
    #修改版
    def find(word,letter,start):
        index =start
        while index<len(word):
            if word[index]==letter:
                return index
            index = index +1
        return -1
  1. 改良count函数 ,泛化它以接收字符串和要计数的字母作为参赛
def count(word,find):
    count = 0
    for letter in word:
        if letter==find:
            count = count+1
    return count
  1. ROT13是个比较弱的加密方式,对单词进行位移来实现加密。编写一个rotate_word 接受字符串为参数,返回一个新的字符串 并加密。
def rotate_word(s,n):
    rotate_s = ''
    for i in s:
        rotate_s = rotate_s+ chr(ord(i)+2)
    return rotate_s

术语表():

  • 对象(object):变量可以引用的一种事物,就现在拉说,你可以八对象当做值来使用
  • 序列(sequence):一个有序的集合
  • 项(item):序列中的一个值
  • 下标(index):用于在序列中选择元素的整数值。
  • 切片(slice):字符串的一部分 通过一个下标范围来定位
  • 空字符串(empty string):没有字符 长度为0的字符串
  • 不可变(immutable):序列的一种属性,表示它的元素是不可变的
  • 遍历(traverse):迭代访问序列中的每一个元素,并对每个元素进行相似操作
  • 搜索(search):一种遍历模式,当找到它想要的元素时停止
  • 计数器(counter):一种用来计数的变量,通常初始化为0 后来会递增
  • 方法(method):和对象关联的一个函数,使用句点表示法来调用
  • 方法调用(invocation):调用一个方法的语句
原文地址:https://www.cnblogs.com/iyueyao/p/4190000.html