天天看點

python自學日記4-字元串python自學日記4-字元串

python自學日記4-字元串

1.for循環

使用for循環周遊字元

由于好久沒用for循環了,有點生疏,竟然寫成了下面代碼

fruit='banana'
len(fruit)
index=0
for index<len(fruit):
    print(fruit[index])
    index+=1
           

File “”, line 3

for index<len(fruit):

^

SyntaxError: invalid syntax

報錯是肯定的了,這是把for循環和while循環雜糅了,還是應該注意下for循環和while循環的差別

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

這個是能正常列印的,但是while确實不适合做周遊循環,用for會更簡單一些

for char in fruit:
    print(char)
           

2.字元串方法

這裡記錄兩個replace和strip

#str.replace(old,new[,count]) []表示裡面的是可選,count,表示隻替換前count次出現
word='banana'
word.replace('na','se')
word.replace('na','se',1)#隻替換了第一個na
           
#str.strip([chars]) 預設移除前後的空格,輸入chars則移除chars
'   hello   '.strip()
'www.example.com'.strip('cmowz.')
           
#strip從開頭和結尾分别向中間篩選,遇到第一個非chars則停止
a='#.......section 3.2.1 issue #32.......'
a.strip('.#!')#從此結果看出,中間的 .和#都沒有被移除,因為前面都有不是chars的部分 
           

輸出結果是:‘section 3.2.1 issue #32’

3.比較兩個單詞,如果互為倒序則傳回True

def is_reverse(word1,word2):
    if len(word1)!=len(word2):
        return False
    i=0
    j=len(word2)-1 #注意需要減一,否則會超出下标範圍
    while j>=0: #注意要大于等于0,而不是大于0,否則會少比較一個
        if word1[i]!=word2[j]:
            return False
        i+=1
        j-=1
    return True
is_reverse('stp','pots')
           

4.以前寫過一個回文的函數比較麻煩,這次通過[::-1]來測試單詞是不是回文會簡單很多

def is_palindrome(word):
    if word==word[::-1]:
        return True
    return False
is_palindrome('helleh')
           

題目中有些用一行把這個函數寫出來,說到一行我首先想到就是用lambda函數,思來想去寫出了如下代碼:

is_palindrome=lambda word:(True if word==word[::1],False)
is_palindrome('hello')
           
File "<ipython-input-55-363d8c65fb6a>", line 2
    is_palindrome=lambda word:(True if word==word[::1],False)
                                                      ^
SyntaxError: invalid syntax
           

結果就報錯了嘛,上網查了下lambda是不能用if語句的,後面有機會詳細補充下lambda的用法以及其和def函數的差別

5.練習:ROT13字元串輪轉加密

編寫一個函數rotate_word,接收一個字元串以及一個整數作為參數,并傳回一個新字元串,其中字母按照給定的整數值輪轉位置,‘A’移動3個位置是’D’,‘Z’移動1個位置是’A’.

def rotate_word(word,num):
    new_word=''
    for letter in word:
        new_word.append(chr(ord(letter)+num))
    return new_word
rotate_word('a',1)
           
AttributeError                            Traceback (most recent call last)
<ipython-input-64-4664c16d8869> in <module>
      5         new_word.append(chr(ord(letter)+num))
      6     return new_word
----> 7 rotate_word('a',1)

<ipython-input-64-4664c16d8869> in rotate_word(word, num)
      3     new_word=''
      4     for letter in word:
----> 5         new_word.append(chr(ord(letter)+num))
      6     return new_word
      7 rotate_word('a',1)

AttributeError: 'str' object has no attribute 'append'
           

第一次直接寫成上面,報錯提示str是不能用append的,是以改成’+’

def rotate_word(word,num):
    new_word=''
    for letter in word:
        new_word=new_word+(chr(ord(letter)+num))#這個位置改動
    return new_word
rotate_word('Z',1)
           

但是輸出結果預期是’A’,但顯示的是’[’,這顯然是對Unicode不熟悉,以及對題目沒有把握好,首先我測了下’a’和’A’的Unicode值,為了能使Z加1變成A,需要經過一些計算,先把一個字母減掉初始值,如果是大寫的減A的值,然後加要移動的值,再加26,然後對26取餘,得出來的餘數再加初始值就得到最終字母的Unicode了,然後再轉換為字母即可,這裡有個注意的地方,大寫對應初始是A,小寫對應初始是a。

def rotate_word(word,num):
    new_word=''
    for letter in word:
        if letter.isupper():
            start=ord('A')#ord函數将字母轉換為Unicode點的整數
        elif letter.islower():
            start=ord('a')
        #chr函數将數值編碼轉換為字元
        new_word=new_word+(chr((ord(letter)-start+num+26)%26+start))
    return new_word
rotate_word('melon',-10)
           

我這有個不好的毛病就是習慣把一系列運算寫到一行,拆解一下或許更容易看

下面是答案的代碼

import string


def rotate_letter(letter, n):
    """Rotates a letter by n places.  Does not change other chars.

    letter: single-letter string
    n: int

    Returns: single-letter string
    """
    if letter.isupper():
        start = ord('A')
    elif letter.islower():
        start = ord('a')
    else:
        return letter

    c = ord(letter) - start
    i = (c + n) % 26 + start
    return chr(i)


def rotate_word(word, n):
    """Rotates a word by n places.

    word: string
    n: integer

    Returns: string
    """
    res = ''
    for letter in word:
        res += rotate_letter(letter, n)
    return res


if __name__ == '__main__':
	print(rotate_word('cheer',7))
           

答案用了兩個函數,而且都寫好了文檔字元串,顯得比較容易讀,以後也應該學着寫文檔字元串。