Reading Notes III:Think Python

字符串取數

a[0]:取出第一位
a[-1]:取出最后一位
a[1:-1]: 取出除開頭核結尾的位
a[::-1]:字段倒敘輸出

回文判斷

def first(word):
    """Returns the first character of a string."""
    return word[0]
def last(word):
    """Returns the last of a string."""
    return word[-1]
def middle(word):
    """Returns all but the first and last characters of a string."""
    return word[1:-1]
def is_palindrome(word):
    """Returns True if word is a palindrome."""
    if len(word) <= 1:
        return True
    if first(word) != last(word):
        return False
    return is_palindrome(middle(word))
常用函數
fruit='banana'
fruit.count('a')  #統(tǒng)計字母個數,輸出結果:3
fruit.capitalize() #首字母大寫,輸出結果:Banana
fruit.[0:5:2] #返回特定位置上的數,輸出結果:bnn
fruit.center(20,'*') #使字段居中,輸出結果:'*******banana*******'
fruit.endswith("a") #判斷最后一位,返回True
fruit.endswith("n") #返回False
fruit.rfind("na") #返回最大位包含字符串的,返回4
fruit.lstrip() #去掉左邊的空格
Chapter 8 Exercise 8.5.
def rotate_word(alpha,num):   
    new=''
    for a in range(0,len(alpha)):
        if a<=len(alpha)-1:
            new=new+chr(ord(alpha[a])+num)
            a+=1
    return new #輸出示例:rotate_word("AB",2):CD
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容