zoukankan      html  css  js  c++  java
  • think python 第8章字符串

    8.1字符串是一个序列

    8.2len

    8.3traveral with a for loop

    1.通过while循环遍历字符串

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

    2.通过for循环遍历

    f = 'fruit'
    for i in f:
        print(i)

    8.4string slices

    数组[a:b] 左闭右开

    8.5 strings are immutable

    字符串是不可变的,即不可以修改一个已经存在的字符。如果我们想把‘hello,world’改变为‘hello,python’

    string1 = 'hello,world'
    string2 = string1[:6] + 'python'
    print(string2)

    8.6searching

    def find(word,letter):
        index = 0
      # 读取字符串单字符的下标
        while index < len(word)
            if word[index] == letter 
                return index
            index += 1
        return -1

    8.7looping and counting

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

    封装起来:

    def count(word,leter):
    number = 0
    for i in word:
        if i == letter:
            number += 1
    print(number)

    也可以这样来封装(其实是一样的)

    word = input('the word is:')
    letter = input("the letter is:")
    def count(word,letter):
        number = 0
        for i in word:
            if i == letter:
                number += 1
        return number
    print(count(word,letter))

    8.8string methods

    语法(函数) == 方法.语法()

    8.9in运算符

    8.10string comparison

    字符串的‘大小’比较:

    (1)大写祖母小于小写字母;

    (2)按顺序每个字母进行比较,一旦不一致,只需比较这个即可,后面的不用理会

    (3)banana < bananas

    8.11debugging

    修改后的代码如下:

    def is_reverse(word1,word2):
        if len(word1) != len(word2):
            return False
        else:
            i = 0
            j = len(word2) -1
            while j >= 0:
                if word1[i] != word2[j-1]:
                    return False
                i += 1
                j -= 1                          
            return True

    8.13exercises

    例题8.10 首先用第6章的方法实现回文单词

    def first(word):
        return word[0]
    def last(word):
        return word[-1]
    def middle(word):
        return word[1:-1]
    def is_palindrome(word):
        if len(word) <= 1:
            return True
        if first(word) != last(word):
            return False
        return is_palindrome(middle(word))
    print is_palindrome('allen')#语法错误?
    print is_palindrome('bob')
    print is_palindrome('otto')
    print is_palindrome('a')
    print is_palindrome('')

    还可以这样来实现回文单词的判定:

    def is_palindrome(word):
        if word[::-1] == word:
            return True
        else:
            return False
  • 相关阅读:
    题解 [BZOJ1295][SCOI2009] 最长距离
    题解 [51nod1274] 最长递增路径
    #leetcode刷题之路21-合并两个有序链表
    #leetcode刷题之路20-有效的括号
    #leetcode刷题之路19-删除链表的倒数第N个节点
    #leetcode刷题之路18-四数之和
    #leetcode刷题之路17-电话号码的字母组合
    #leetcode刷题之路16-最接近的三数之和
    #leetcode刷题之路15-三数之和
    #leetcode刷题之路14-最长公共前缀
  • 原文地址:https://www.cnblogs.com/Kingwjk/p/7886647.html
Copyright © 2011-2022 走看看