Python核心编程第二版第六章序列:字符串,列表和元组(课后习题)----我的答案

本文主要探讨Python中的序列操作,包括字符串的方法,如查找子串、排序、算术运算、字符串处理和调试。同时介绍了列表的使用,如生成英文表示的整数、时间转换以及字符串大小写的翻转。还涉及了IP地址转换、矩阵操作和列表的存储与处理。通过一系列编程练习,提升对Python序列和字符串的理解和应用。
摘要由CSDN通过智能技术生成

6-1.字符串。string模块中是否有一种字符串方法或者函数可以帮我鉴定下一个字符串是否是另一个大字符串的一部分?

判断一个字符串是否包含另一个字符串: find()、index()、rfind()、rindex()

import string
s = 'sdadaadaa'
print s.find('dad')
print s.index('sda')

6-2.字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kwlist)来帮你.

import string
import keyword

alphas = string.letters + '_'
nums = string.digits
kw = keyword.kwlist

print 'Welcome to the Identifier Checker v1.1'
print 'Now we can check keyword.'
print 'Teatees must be at least 1 chars long.'
myInput = raw_input('Identifier to test?')

if len(myInput) > 0:
    if myInput[0] not in alphas:
        print '''invalid: first symbol must be alphabetic'''
    elif myInput in kw:
        print 'that is a keyword in Python'
    else:
        for otherChar in myInput[1:]:

            if otherChar not in alphas + nums:
                print '''invalid: remaining
                    symbols must be alphanumeric'''
                break
        else:
            print "okay as an identifier"

6-3.排序

(a).输入一串数字,并从小到大排列之。

aList = [1, 2, 7, 8 ,4, 3]
aList.sort()
print aList

(b).跟a一样。不过要用字典序从小到大排列

aList = {'name': 'cytus', 'age': 18, 'like': 'dog'}
print sorted(aList.keys())
print sorted(aList.items(), key= lambda item:item[1])

6-4.算术。更新上一章里面你的得分测试练习方法方案,把测试得分放到一个列表中去。你的代码可以算出一个平均数。

def testScore():
    if score >= '90' and score <= '100':
        print("Your testscore is A.")
    elif score >= '80' and score <= '89':
        pr
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值