字符串取數
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