美文网首页
Reading Notes III:Think Python

Reading Notes III:Think Python

作者: 冬季男孩 | 来源:发表于2021-01-29 12:26 被阅读0次
字符串取数

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')  #统计字母个数,输出结果: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

相关文章

网友评论

      本文标题:Reading Notes III:Think Python

      本文链接:https://www.haomeiwen.com/subject/jnaszktx.html