1. 字符串推导式

我们之前学过列表推导式。例如,生成前 4 个奇数,我们可以写

[2 * num - 1 for num in range(1,5)] # 生成[1, 3, 5, 7]

仿照上面写法,使用推导式完成以下字符串操作:

  1. [‘apple’, ‘orange’, ‘pear’] -> [‘A’, ‘O’, ‘P’] # 第一个字母大写
  2. [‘apple’, ‘orange’, ‘pear’] -> [‘apple’, ‘pear’] # 是否包含字母’p’
  3. [“TA_parth”, “student_poohbear”, “TA_michael”, “TA_guido”, “student_
    htiek”] -> [“parth”, “michael”, “guido”] #是否以 TA_开头
  4. [‘apple’, ‘orange’, ‘pear’] -> [(‘apple’, 5), (‘orange’, 6), (‘pear’, 4)]
    #生成列表
  5. [‘apple’, ‘orange’, ‘pear’] -> {‘apple’: 5, ‘orange’: 6, ‘pear’: 4} #生成字典
list1 = ['apple', 'orange', 'pear']
print([i[0].upper() for i in list1])list2 = ['apple', 'orange', 'pear']
print([i for i in list2 if i.count('p') > 0])list3 = ["TA_parth",  "student_poohbear","TA_michael",  "TA_guido",  "student_htiek"]
print([i[3:] for i in list3 if i.startswith('TA_')])list4 = ['apple', 'orange', 'pear']
print([{i, len(i)} for i in list4])list5 = ['apple', 'orange', 'pear']
print({i: len(i) for i in list5})

2. 特殊单词

有一种特殊的英文单词,它的相邻字母对之间的“距离”不断增加。如单词 subway,它的相邻字母对分别为 (s, u), (u, b), (b, w), (w, a), (a, y), 字母之间的距离依次为 2,19,21,22,24(如 a 是第 1 个字母,y 是第 25 个字母,a 和 y 的距离为 24)。编写函数is_special_word(word),word 为输入单词字符串,如为特殊单词,返回 True;否则返回 False。

import stringdic = {i: string.ascii_lowercase.find(i) + 1 for i in string.ascii_lowercase}def is_special_word(word):for i in range(len(word)-2):if abs(dic[word[i+2]]-dic[word[i+1]]) < abs(dic[word[i+1]]-dic[word[i]]):return False
return True
word = str(input("请输入单词:"))
print(is_special_word(word))

3. Caesar 加密

Caesar 加密将文本中每个字符向前移动三个字母,即A->D,B->E,…,X->A,Y->B,Z->C如单词 PYTHON,将加密为 SBWKRQ。编写加密函数 encrypt_caesar(plaintext)和decrypt_caesar(ciphertext),每个函数都接受一个参数,表示将要加密或解密的字符串,然后返回加密或解密之后的字符串。

注:(1)只考虑大写字母;(2)非字母字符不需要通过加密或解密来修改。如encrypt_caesar(“F1RST
P0ST”)应该返回“I1UVW S0VW”;(3)encrypt_caesar(“”)应返回“”,即空字符串。

import stringdef encrypt_caesar(plaintext):before = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'after = 'DEFGHIJKLMNOPQRSTUVWXYZABC'table = ''.maketrans(before, after)
return plaintext.translate(table)def decrypt_caesar(ciphertext):after = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'before = 'DEFGHIJKLMNOPQRSTUVWXYZABC'table = ''.maketrans(before, after)return ciphertext.translate(table)word1 = str(input("请输入加密单词:"))
print(encrypt_caesar(word1))
word1 = str(input("请输入解密单词:"))
print(decrypt_caesar(word1))

4. 杨辉三角

编写函数 print_yanghui_triangle(N),输出杨辉三角的前 N 行,要求使用 format 函数进行格式化输出

def print_yanghui_triangle(N):triangle = [['1'] for i in range(N)]for i in range(1, N):triangle[i].extend(str(int(triangle[i-1][j])+int(triangle[i-1][j+1]))for j in range(len(triangle[i-1])-1))triangle[i].append('1')for i in range(len(triangle)):# print('{:^30}'.format(' '.join(triangle[i])))print(' '.join(triangle[i]).center(len(' '.join(triangle[N-1]))))N = int(input('N:'))
print_yanghui_triangle(N)

Center方法:

Format方法:

5. 可读性等级

不同书的阅读群体不一样。例如,一本书中可能有许多很长的复杂单词;而较长的单词可能与较高的阅读水平有关。同样,较长的句子也可能与较高的阅读水平相关。研究者开发了许多可读性测试,给出了计算文本阅读水平的公式化过程。其中一个可读性测试是 Coleman Liau 指标:文本的 Coleman Liau 指标旨在划分理解文本所需的阅读水平等级。Coleman Liau 指标公式如下

index = 0.0588 * L - 0.296 * S - 15.8

其中,L 是文本中每 100 个单词的平均字母数,S 是文本中每 100 个单词的平均句子数。

考虑以下文本:

Congratulations! Today is your day. You’re off to Great Places! You’re
off and away!

该文本有 65 个字母,4 个句子,14 个单词。文本中每 100 个单词的平均字母数是L=65/14100=464.29;文本中每 100 个单词的平均句子数是 S=4/14100=28.57。代入 Coleman Liau 指标公式,并向最近的整数取整,我们得到可读性指数为 3级。

我们将编写一个函数 readability,输入参数为字符串,返回可读性等级。

实现要求:

(1) 若计算结果小于 1,输出“Before Grade 1”;
(2) 若计算结果大于或等于 16,输出“Grade 16+”;
(3) 除(1)和(2)外,输出“Grade X”,X 为相应等级。
(4) 字母包括大写字母和小写字母(不考虑数字和标点符号);
(5) 以空格分隔作为标准区分单词,如
It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him.
55 words
(6) 句号(.)、感叹号(!)或问号(?)表示句子的结尾。如
Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.
3 sentences
(7) 可读性等级的参考例子见 readability.txt。

import redef readability(passage):word_num = len(passage.split())
sentence_num = len(re.split('[.?!]', passage))-1alpha_num = 0for i in range(len(passage)):if passage[i].isalpha():alpha_num += 1L = alpha_num/word_num*100S = sentence_num/word_num*100
return round(0.0588*L-0.296*S-15.8)sentence_list = ["One fish. Two fish. Red fish. Blue fish.","Would you like them here or there? I would not like them here or there. I would not like them anywhere.","Congratulations! Today is your day. You're off to Great Places! You're off and away!","Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework, but was forced to do it in secret, in the dead of the night. And he also happened to be a wizard.","In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.","When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow. When it healed, and Jem's fears of never being able to play football were assuaged, he was seldom self-conscious about his injury. His left arm was somewhat shorter than his right; when he stood or walked, the back of his hand was at right angles to his body, his thumb parallel to his thigh.","There are more things in Heaven and Earth, Horatio, than are dreamt of in your philosophy.","It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him.","A large class of computational problems involve the determination of properties of graphs, digraphs, integers, arrays of integers, finite families of finite sets, boolean formulas and elements of other countable domains."]
for sentence in sentence_list:index = readability(sentence)if index < 1:print('Before Grade 1')elif index >= 16:print('Grade 16+')else:print('Grade', index)

【Python程序设计】字符串的应用相关推荐

  1. 【浙大版《Python 程序设计》题目集(解)】第3章-14 字符串字母大小写转换(15分)

    本题要求编写程序,对一个以"#"结束的字符串,将其小写字母全部转换成大写字母,把大写字母全部转换成小写字母,其他字符不变输出. 输入格式: 输入为一个以"#"结 ...

  2. Python 程序设计(第二版)董付国_清华大学出版社_习题答案与分析【针对8.4及其之前的】

    更多精彩内容:(没有设置公众号获得,麻烦动动小手~谢谢) CSDN下载:Python编程无师自通电子书,[美]科里·奥尔索夫(Cory Althoff)-文档类-CSDN下载 百度云:链接:https ...

  3. 《Python程序设计》题库(2)

    侵权联系我删除: [写在这里,方便右键百度搜索!] <Python程序设计>题库 填空题 Python安装扩展库常用的是_______工具.(pip) Python标准库math中用来计算 ...

  4. python程序设计试卷_Python程序设计试题库

    < Python 程序设计>题库 一.填空题 第一章基础知识 1 . Python 安装扩展库常用的是 ________ 具.( pip ) 2 . Python 标准库 math 中用来 ...

  5. python设计选择题代码_《Python程序设计》试题库

    WORD 完美格式 < Python 程序设计>题库 一.填空题 第一章 基础知识 1 . Python 安装扩展库常用的是 _______ 工具.( pip ) 2 . Python 标 ...

  6. python程序设计梁勇 百度网盘_20194220 2019-2020-2 《Python程序设计》实验二报告

    20194220 2019-2020-2 <Python程序设计>实验二报告 课程:<Python程序设计> 班级: 1942 姓名: 梁勇 学号:20194220 实验教师: ...

  7. python笔试题110题_《Python程序设计》试题库

    .. ;. < Python 程序设计>题库 一.填空题 第一章 基础知识 1 . Python 安装扩展库常用的是 _______ 工具.( pip ) 2 . Python 标准库 m ...

  8. python程序设计课后答案祁瑞华_清华大学出版社-图书详情-《Python 程序设计》

    前言 Python语言作为一种免费.开源语言,已被许多学校引入教学过程.它是面向对象和过程的程序设计语言,具有丰富的数据结构.可移植性强.语言简洁.程序可读性强等特点.本书根据实际教学经验,对内容进行 ...

  9. python程序设计 清华大学出版社 pdf下载-清华大学出版社-图书详情-《Python程序设计》...

    前 言 Python是一种解释型的.面向对象的.带有动态语义的高级编程语言.它由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年.经过二十多年的发展,Pytho ...

  10. python程序设计 清华大学出版社 pdf下载-清华大学出版社-图书详情-《Python 程序设计》...

    前言 Python语言作为一种免费.开源语言,已被许多学校引入教学过程.它是面向对象和过程的程序设计语言,具有丰富的数据结构.可移植性强.语言简洁.程序可读性强等特点.本书根据实际教学经验,对内容进行 ...

最新文章

  1. 刷新4项文档智能任务纪录,百度TextMind打造ERNIE-Layout登顶文档智能权威榜单
  2. python输出奇数数字序位_python对输出的奇数偶数排序实例代码
  3. 蒙古族女孩鲍尔金娜的小说《紫茗红菱》
  4. Js对象如何添加方法、查看Api
  5. 下列哪项属于正确的锁定计算机桌面,【2018年职称计算机考试WindowsXp练习题及答案1】- 环球网校...
  6. C++PrimerPlus学习——第九章编程练习
  7. MVC微信浏览器图片上传(img转Base64)
  8. mysql 分区表_MySQL 分区分表应用场景分析和分区中可能遇到的坑点
  9. Rust+Yew之hello world
  10. Java并发编程实战笔记—— 并发编程1
  11. JQuery 为radio赋值问题
  12. 王者荣耀新英雄官宣:鲁班七号之父鲁班大师 即将上线
  13. redis复习(参考书籍redis设计与实现)
  14. java excel 日期格式转换_Java处理Excel中的日期格式
  15. 这种技术能够替代 Android 原生开发?
  16. 项目分析 移动终端自助点餐系统
  17. 罗素“杀死了”康托尔
  18. 图片裁剪工具vue-img-cutter
  19. 南柯服务器压力,南柯梦崇洋(十一)
  20. 关于网站域名备案流程

热门文章

  1. 相机模型之鱼眼模型(Equidistant)
  2. 奇文共赏(经典博客总结)
  3. #git操作#拉取远程分支到本地,克隆远程分支的代码(指定分支)
  4. 头脑风暴之零钱兑换,扩散你的思维
  5. Java虚拟机是如何加载Java类的?
  6. f开头的流媒体软件_流媒体服务引擎
  7. 评估指标及代码实现(NDCG)
  8. Java基本数据类型的Class问题
  9. 记录Win10+Ubuntu18.04(引导Win10启动)双系统迁移到SSD,Ubuntu迁移成功但丢失Win10启动项
  10. php 重定向 无效,php – 重定向头功能不起作用