Chapter 7: Strings | Python for Everybody 讲义笔记_En

news2024/10/5 14:34:04

文章目录

  • Python for Everybody
    • 课程简介
    • Strings
      • A string is a sequence
      • Getting the length of a string using `len`
      • Traversal through a string with a loop
      • String slices
      • Strings are immutable
      • Looping and counting
      • The `in` operator
      • String comparison
      • String methods
      • Parsing strings
      • Format operator
      • Debugging
      • Glossary


Python for Everybody

Exploring Data Using Python 3
Dr. Charles R. Severance


课程简介

Python for Everybody 零基础程序设计(Python 入门)

  • This course aims to teach everyone the basics of programming computers using Python. 本课程旨在向所有人传授使用 Python 进行计算机编程的基础知识。
  • We cover the basics of how one constructs a program from a series of simple instructions in Python. 我们介绍了如何通过 Python 中的一系列简单指令构建程序的基础知识。
  • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. 该课程没有任何先决条件,除了最简单的数学之外,避免了所有内容。任何具有中等计算机经验的人都应该能够掌握本课程中的材料。
  • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. 本课程将涵盖《Python for Everyday》教科书的第 1-5 章。学生完成本课程后,他们将准备好学习更高级的编程课程。
  • This course covers Python 3.

在这里插入图片描述

coursera

Python for Everybody 零基础程序设计(Python 入门)

Charles Russell Severance
Clinical Professor

在这里插入图片描述

个人主页
Twitter

在这里插入图片描述

University of Michigan


课程资源

coursera原版课程视频
coursera原版视频-中英文精校字幕-B站
Dr. Chuck官方翻录版视频-机器翻译字幕-B站

PY4E-课程配套练习
Dr. Chuck Online - 系列课程开源官网



Strings

We look at how Python stores and manipulates textual data using string variables and functions.


A string is a sequence

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana'
>>> letter = fruit[1]

The second statement extracts the character at index position 1 from the fruit variable and assigns it to the letter variable.

The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name).

But you might not get what you expect:

>>> print(letter)
a

For most people, the first letter of “banana” is “b”, not “a”. But in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0]
>>> print(letter)
b

So “b” is the 0th letter (“zero-th”) of “banana”, “a” is the 1th letter (“one-th”), and “n” is the 2th (“two-th”) letter.


在这里插入图片描述


String Indexes

You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5]
TypeError: string indices must be integers

Getting the length of a string using len

len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana'
>>> len(fruit)
6

To get the last letter of a string, you might be tempted to try something like this:

>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

The reason for the IndexError is that there is no letter in “banana” with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

>>> last = fruit[length-1]
>>> print(last)
a

Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.

Traversal through a string with a loop

A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:

index = 0
while index < len(fruit):
    letter = fruit[index]
    print(letter)
    index = index + 1

This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.

Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.

Another way to write a traversal is with a for loop:

for char in fruit:
    print(char)

Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.

String slices

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python'
>>> print(s[0:5])
Monty
>>> print(s[6:12])
Python

The operator [n:m] returns the part of the string from the “n-th” character to the “m-th” character, including the first but excluding the last.

If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:

>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:

>>> fruit = 'banana'
>>> fruit[3:3]
''

An empty string contains no characters and has length 0, but other than that, it is the same as any other string.

Exercise 2: Given that fruit is a string, what does fruit[:] mean?

Strings are immutable

It is tempting to use the operator on the left side of an assignment, with the intention of changing a character in a string. For example:

>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment

The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence.

The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:

>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print(new_greeting)
Jello, world!

This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.

Looping and counting

The following program counts the number of times the letter “a” appears in a string:

word = 'banana'
count = 0
for letter in word:
    if letter == 'a':
        count = count + 1
print(count)

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an “a” is found. When the loop exits, count contains the result: the total number of a’s.

Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.

The in operator

The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

String comparison

The comparison operators work on strings. To see if two strings are equal:

if word == 'banana':
    print('All right, bananas.')

Other comparison operations are useful for putting words in alphabetical order:

if word < 'banana':
    print('Your word,' + word + ', comes before banana.')
elif word > 'banana':
    print('Your word,' + word + ', comes after banana.')
else:
    print('All right, bananas.')

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:

Your word, Pineapple, comes before banana.

A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

String methods

Strings are an example of Python objects. An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object.

Python has a function called dir which lists the methods available for an object. The type function shows the type of an object and the dir function shows the available methods.

>>> stuff = 'Hello world'
>>> type(stuff)
<class 'str'>
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>> help(str.capitalize)
Help on method_descriptor:

capitalize(...)
    S.capitalize() -> str

    Return a capitalized version of S, i.e. make the first character
    have upper case and the rest lower case.
>>>

While the dir function lists the methods, and you can use help to get some simple documentation on a method, a better source of documentation for string methods would be https://docs.python.org/library/stdtypes.html#string-methods.

Calling a method is similar to calling a function (it takes arguments and returns a value) but the syntax is different. We call a method by appending the method name to the variable name using the period as a delimiter.

For example, the method upper takes a string and returns a new string with all uppercase letters:

Instead of the function syntax upper(word), it uses the method syntax word.upper().

>>> word = 'banana'
>>> new_word = word.upper()
>>> print(new_word)
BANANA

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument.

A method call is called an invocation; in this case, we would say that we are invoking upper on the word.

For example, there is a string method named find that searches for the position of one string within another:

>>> word = 'banana'
>>> index = word.find('a')
>>> print(index)
1

In this example, we invoke find on word and pass the letter we are looking for as a parameter.

The find method can find substrings as well as characters:

>>> word.find('na')
2

It can take as a second argument the index where it should start:

>>> word.find('na', 3)
4

One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a string using the strip method:

>>> line = '  Here we go  '
>>> line.strip()
'Here we go'

Some methods such as startswith return boolean values.

>>> line = 'Have a nice day'
>>> line.startswith('Have')
True
>>> line.startswith('h')
False

You will note that startswith requires case to match, so sometimes we take a line and map it all to lowercase before we do any checking using the lower method.

>>> line = 'Have a nice day'
>>> line.startswith('h')
False
>>> line.lower()
'have a nice day'
>>> line.lower().startswith('h')
True

In the last example, the method lower is called and then we use startswith to see if the resulting lowercase string starts with the letter “h”. As long as we are careful with the order, we can make multiple method calls in a single expression.

Exercise 4: There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method at:

https://docs.python.org/library/stdtypes.html#string-methods

Write an invocation that counts the number of times the letter a occurs in “banana”.

Parsing strings

Often, we want to look into a string and find a substring. For example if we were presented a series of lines formatted as follows:

From stephen.marquard@ uct.ac.za Sat Jan 5 09:14:16 2008

and we wanted to pull out only the second half of the address (i.e., uct.ac.za) from each line, we can do this by using the find method and string slicing.

First, we will find the position of the at-sign in the string. Then we will find the position of the first space after the at-sign. And then we will use string slicing to extract the portion of the string which we are looking for.

>>> data = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
>>> atpos = data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1:sppos]
>>> print(host)
uct.ac.za
>>>

We use a version of the find method which allows us to specify a position in the string where we want find to start looking. When we slice, we extract the characters from “one beyond the at-sign through up to but not including the space character”.

The documentation for the find method is available at

https://docs.python.org/library/stdtypes.html#string-methods.

Format operator

The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator.

The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string.

For example, the format sequence %d means that the second operand should be formatted as an integer (“d” stands for “decimal”):

>>> camels = 42
>>> '%d' % camels
'42'

The result is the string ‘42’, which is not to be confused with the integer value 42.

A format sequence can appear anywhere in the string, so you can embed a value in a sentence:

>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'

If there is more than one format sequence in the string, the second argument has to be a tuple1. Each format sequence is matched with an element of the tuple, in order.

The following example uses %d to format an integer, %g to format a floating-point number (don’t ask why), and %s to format a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple must match the number of format sequences in the string. The types of the elements also must match the format sequences:

>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str

In the first example, there aren’t enough elements; in the second, the element is the wrong type.

The format operator is powerful, but it can be difficult to use. You can read more about it at

https://docs.python.org/library/stdtypes.html#printf-style-string-formatting.

Debugging

A skill that you should cultivate as you program is always asking yourself, “What could go wrong here?” or alternatively, “What crazy thing might our user do to crash our (seemingly) perfect program?”

For example, look at the program which we used to demonstrate the while loop in the chapter on iteration:

while True:
    line = input('> ')
    if line[0] == '#':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')

# Code: http://www.py4e.com/code3/copytildone2.py

Look what happens when the user enters an empty line of input:

> hello there
hello there
> # don't print this
> print this!
print this!
>
Traceback (most recent call last):
  File "copytildone.py", line 3, in <module>
    if line[0] == '#':
IndexError: string index out of range

The code works fine until it is presented an empty line. Then there is no zero-th character, so we get a traceback. There are two solutions to this to make line three “safe” even if the line is empty.

One possibility is to simply use the startswith method which returns False if the string is empty.

if line.startswith('#'):

Another way is to safely write the if statement using the guardian pattern and make sure the second logical expression is evaluated only where there is at least one character in the string:

if len(line) > 0 and line[0] == '#':

Glossary

counter
A variable used to count something, usually initialized to zero and then incremented.
empty string
A string with no characters and length 0, represented by two quotation marks.
format operator
An operator, %, that takes a format string and a tuple and generates a string that includes the elements of the tuple formatted as specified by the format string.
format sequence
A sequence of characters in a format string, like %d, that specifies how a value should be formatted.
format string
A string, used with the format operator, that contains format sequences.
flag
A boolean variable used to indicate whether a condition is true or false.
invocation
A statement that calls a method.
immutable
The property of a sequence whose items cannot be assigned.
index
An integer value used to select an item in a sequence, such as a character in a string.
item
One of the values in a sequence.
method
A function that is associated with an object and called using dot notation.
object
Something a variable can refer to. For now, you can use “object” and “value” interchangeably.
search
A pattern of traversal that stops when it finds what it is looking for.
sequence
An ordered set; that is, a set of values where each value is identified by an integer index.
slice
A part of a string specified by a range of indices.
traverse
To iterate through the items in a sequence, performing a similar operation on each.


  1. A tuple is a sequence of comma-separated values inside a pair of parenthesis. We will cover tuples in Chapter 10 ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/745488.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

x86平台实时Windows机器视觉EtherCAT运动控制器VPLC711

一、市场背景 简单易用&#xff0c;功能强大&#xff0c;正运动技术持续专注智能制造核心控制器的产品与平台的突破&#xff01; 随着智能制造的兴起&#xff0c;制造型企业正面临着日益激烈的市场竞争和对生产效率与产品品质提升的迫切需求&#xff0c;以满足市场的要求。同…

详解自定义类型:结构体,枚举,联合

目录 结构体 结构体基础知识 结构的自引用 结构体内存对齐 结构体大小计算 存在内存对齐的原因 设计结构体时的技巧 修改默认对齐数 结构体实现位段&#xff08;位段的填充&可移植性&#xff09; 什么是位段 位段的内存分配 位段的跨平台问题 位段的应用 枚…

做数据库内核开发的人员很少吗?

是的&#xff0c;相对于其他领域的软件开发&#xff0c;数据库内核开发人员的数量确实相对较少。这是因为数据库内核开发是一项高度专业化和复杂的任务&#xff0c;需要深入理解数据库系统的原理、算法和底层技术。 我这里刚好有嵌入式、单片机、plc的资料需要可以私我或在评论…

和鲸数据科学专家平台正式成立,凝聚专家资源推进产业数字化升级

2015年&#xff0c;大数据与人工智能从技术到公众认知均迎来重大突破&#xff0c;全国首批“数据科学与大数据技术”专业获批 同年&#xff0c;和鲸科技的前身科赛网 Kesci 正式成立&#xff0c;从数据竞赛社区出发为“数据人”提供实践与成长的平台。 2023年&#xff0c;数据…

sql语句汇总

最近项目中接触到了mySql,把经常用到的MySql语句记录下来&#xff0c;方便以后随时查阅。 1.密码加密 表结构如下 INSERT INTO tbl_userinfo ( vc_accname,vc_username,vc_pwd,vc_phone,i_role_id,dt_creatTime) VALUES (%s,%s,AES_ENCRYPT((%s), Wang),%s,%d,NOW())该表主…

Shiro教程(二):Springboot整合Shiro全网最全教程

Shiro教程&#xff08;二&#xff09;&#xff1a;Springboot整合Shiro全网最全教程 1、SpringBoot整合Shiro环境搭建 新建Module 新建springboot项目 选择一个依赖就行&#xff0c;因为这里idea版本的问题&#xff0c;SpringBoot的版本最低就是2.7.13。可以等项目创建成功之后…

无需下载任何软件!BurpSuite如何抓取iphone数据包

一、手机电脑处于同一个网段下 此处我的手机和电脑都处在X.X.1.X网段下 二、BurpSuite设置 添加代理 手机端配置代理 配置完点击存储 三、手机导入证书文件 手机端在Safari浏览器输入【电脑端ip:8080】 允许 在设置里打开 “已下载描述文件” 选择安装&#xff08;因为我已…

第五课:Figma 玻璃拟态页设计

效果展示 通过背景模糊实现玻璃拟态效果 选择合适的背景&#xff0c;绘制形状&#xff0c;给形状添加 Effects&#xff0c;点击下方的下拉选择框&#xff0c;选择 background blur&#xff1b;添加后会发现&#xff0c;画面无任何改变&#xff0c;调整 Fill 后面的百分比&…

【JavaEE进阶】使用注解存储对象

使用注解存储对象 之前我们存储Bean时&#xff0c;需要在spring-config 中添加一行 bean注册内容才行&#xff0c;如下图所示&#xff1a; 问题引入&#xff1a;如果想在Spring 中能够更简单的进行对象的存储和读取&#xff0c;该怎么办呢&#xff1f; 问题解答&#xff1a;实…

【c++】std::move 所有权转移的使用

1. std::move用法详细梳理 ref_frames_ std::move(ref_frames);cur_frames_ cur_frames;使用std::move函数的好处是可以将资源的所有权从一个对象转移到另一个对象&#xff0c;而不需要进行深拷贝操作。对于智能指针类型的变量&#xff0c;使用std::move也是可以的&#xff0…

K8s(kubernetes)集群搭建及dashboard安装、基础应用部署

基础介绍 概念 本质是一组服务器集群&#xff0c;在集群每个节点上运行特定的程序&#xff0c;来对节点中的容器进行管理。实现资源管理的自动化。 功能 自我修复弹性伸缩服务发现负载均衡版本回退存储编排 组件 控制节点(master)-控制平面 APIserver&#xff1a;资源操作…

VMware ESXi 7.0 Update 3n - 领先的裸机 Hypervisor

VMware ESXi 7.0 Update 3n - 领先的裸机 Hypervisor VMware ESXi 7.0 Update 3n Standard & All Custom Image for ESXi 7.0 U3m Install CD 更新日期&#xff1a;Fri Jul 07 2023 10:50:00 GMT0800&#xff0c;阅读量: 4518 请访问原文链接&#xff1a;https://sysin.…

全网最细,Web自动化测试-数据驱动实战,直接通关...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 在Web自动化测试中…

智能照明控制系统在民用照明节能中的应用

摘 要 &#xff1a;通过智能照明控制系统在某宾馆电气工程中的应用实例&#xff0c;从照明控制的系统结构、设计及系统软件等方面&#xff0c;介绍了智能照明控制系统的功能及实现方式。探讨了智能照明控制系统在民用建筑中的适用范围和发展前景&#xff0c;并由此进一步推断智…

运维小知识(二)——Linux大容量磁盘分区及挂载

centos系统安装&#xff1a;链接 目录 1.&#x1f353;&#x1f353;命令格式化磁盘 2.&#x1f353;&#x1f353;大容量硬盘分区 3.&#x1f353;&#x1f353;自动挂载 整理不易&#xff0c;欢迎一键三连&#xff01;&#xff01;&#xff01; 新系统装完之后&#xff0…

基于appium的常用元素定位方法

目录 一、元素定位工具 1.uiautomatorviewer.bat 2.appium检查器 二、常用元素定位方法 1.id定位 2.class_name定位 3.accessibility_id定位 4.android_uiautomator定位 5.xpath定位 三、组合定位 四、父子定位 五、兄弟定位 一、元素定位工具 app应用的元素使用的是控…

前端实战(四):Nginx代理

Nginx的用处 Nginx的作用主要体现在作为 Web 服务器、负载均衡服务器、邮件代理服务器等方面&#xff0c;其特点是占有内存少&#xff0c;并发能力强&#xff0c;给使用者带来了很多的便利。Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件&#xff08;IMAP/POP3&…

【UE4 C++】06-绑定运动输入(实现前后移动、鼠标转向)

目录 一、WS前后移动 二、鼠标转向 一、WS前后移动 为了让玩家控制的“PlayerCharacter”能够实现前后移动 在“SCharacter.cpp"中添加如下代码 在“SCharacter.h"中添加如下代码 添加轴映射 设置自动控制玩家 此时按下WS键就可以前进后退了。 二、鼠标转向 …

2023年9月DAMA-CDGA/CDGP认证考试报名开始啦!

据DAMA中国官方网站消息&#xff0c;2023年度第三期DAMA中国CDGA和CDGP认证考试定于2023年9月23日举行。 报名通道现已开启&#xff0c;相关事宜通知如下&#xff1a; 考试科目: 数据治理工程师(CertifiedDataGovernanceAssociate,CDGA) 数据治理专家(CertifiedDataGovernanc…

SQL计算出每年在校人数

以下是一个录取学生人数表的示例&#xff0c;记录了每年录取学生的人数和入学学制。 idyearnumstu_len12018101322019121432020912420211513520211412620221613 字段解释&#xff1a; id&#xff1a;记录的唯一标识符year&#xff1a;学生入学年度num&#xff1a;对应年度录取…