1. 程式人生 > >python核心程式設計第六章

python核心程式設計第六章

6-1 字串。string模組中是否有一種字串方法或者函式可以鑑定一個字串是否是另一個大字串的一部分?

#in/not in 可以判斷一個字串是否再另一個字串中
'bc' in 'abcd'
Out[3]: True

'bc' not in 'abcd'
Out[4]: False

6-2 字串識別符號。修改例6-1的idcheck.py指令碼,使之可以檢測長度為一的識別符號,並且可以識別python關鍵字。對後一個要求,你可以使用keyword模組(特別是keyword.kelist)來輔助。

#標識符合法性檢查,首先要以字母或者下劃線開始,後面要跟字母,下劃線或者數字。
import keyword
import string

test = input('請輸入欄位:')

alphas = string.ascii_letters+'_'    
#在python2中是letters,再python3中是ascii_letters.
nums = string.digits
am = alphas+nums

if len(test) >= 0:
    if test[0] not in alphas:
        print ('首字母不是字母或者下劃線')
    else:
        for a in test[1:]:
            if a not in am:
                print ('字串必須是數字+字母')
                break
        else:  #注意這裡的else要比上面的else往後四個空格
            if test in keyword.kwlist:
                print ('關鍵詞不能作為物件')
            else:
                print ('可以作為識別器')

請輸入欄位:nimen
可以作為識別器