- 例解Python:Python编程快速入门践行指南
- 张志刚
- 1961字
- 2025-02-23 00:06:02
2.2 字符串
2.2.1 常用的定义字符串的方式
Python中,字符串被定义为引号之间的字符集合。引号既可以使用单引号,也可以使用双引号。无论单引号,还是双引号,表示的含义都完全相同。此外,Python支持三引号(三个连续的单引号或双引号),用于包含特殊字符,保存原始格式。如下所示:

为了正确地表示字符串中的单引号,需要在字符串两边使用双引号。如果采用了单引号,就会出现语法错误,因为Python将找到的第二个单引号与第一个单引号实行配对,如下所示:

如果字符串中间有回车,则输入时需要使用转义字符:

三引号能够保存输入时的原始样式,如下所示:

在Python内部保存的时候,并没有分成多行,还是用\n表示回车。不使用print语句,直接输入变量就可以看到Python存储的样式:

2.2.2 通过字符串切片获取字符或子串
使用索引运算符[ ]来得到一个字符。按照从左到右的顺序取字符,第一个字符的索引(也常被称为下标)是0;按照从右到左的顺序取字符,还可以使用负数,最后一个字符的索引是-1。如果使用的下标已经超出范围,则会出现IndexError的异常:

使用切片运算符[:]来得到一部分字符串。冒号左侧是起始下标,右侧是结束下标。其中,起始下标对应的字符包含在子串内,而结束下标对应的字符不包含在子串内。所以取出字符串“Python”的前两个字符,需要使用以下方式:

那么,如果需要取出“thon”呢?字符“n”的下标是5,从下标为2的第三个字符取到下标为5的子串只能取出“tho”:

试一下将结束下标改为6,虽然字符串没有这个下标值:

通过上面的例子,可以得到结论:通过索引运算符取出一个字符,如果索引超出范围会发生错误,而通过切片运算符取子串,下标值可以是任意值。既然6都能用,60是不是也能使用呢?如下所示:

在实际使用过程中,如果想取到结尾,结束下标干脆就不用写了:

同样的道理,从开头取,起始下标也是不用写的:

字符串取切片还支持一个步长值,可以跳跃地取子串,如只想取出“Pto”:

起始下标和结束下标都没有写,表示从头取到尾,步长为2表示每隔一个字符取一个字符。如果只需要取出“yhn”,则如下所示:

步长值也能使用负数,表示自右向左取切片:

2.2.3 字符串的拼接与重复
字符串支持+操作,和数字运算不一样,字符“相加”只是简单地将两个字符串拼接到一起:

只要参与拼接的双方最终都是字符串对象就行,变量py_str是字符串类型,也可以实现拼接操作:

字符串还支持*操作,字符串的*表示将字符串重复多次:

2.2.4 字符串成员关系判断
判断字符或字符串是否存在于另一个字符串中:


2.2.5 字符串方法
字符串拥有非常多方法,这里仅仅将常用的方法做一个简单的说明,完整方法请查阅官方文档,或使用help帮助。
➢ str.strip()。
strip()默认用于去除字符串两端的空白字符。空白字符并不是只有空格,全部的空白字符是" \r\t\v\f\n"。如下所示:

strip()也可以去除两端指定的字符:

如果只是去除左端或右端的字符,则使用lstrip()或rstrip():

➢ str.split()。
split()默认使用空格作为分隔符,将字符串分隔开。

也可以指定分隔符:

➢ str.replace()。
通过名称就能猜到,它用于字符串的替换操作:

➢ str.islower()。
字符串中的字母全部是小写则返回True,不考虑非字母字符:

➢ str.isupper()。
字符串中的字母全部是大写则返回True,不考虑非字母字符:

➢ str.isdigit()。
字符串中所有字符全部是数字才返回True:

➢ str.ljust()。
字符串左对齐:


➢ str.rjust()。
字符串右对齐:

➢ str.center()。
字符串居中:

➢ str.startswith()。
判断字符串以哪些字符开头:

➢ str.endswith()。
判断字符串以哪些字符结尾:

2.2.6 字符串格式化方法
如果字符串中有变化的数据,则可以用%s进行占位:

在中间%的前面有一个字符串,字符串中有两个%s进行占位,这两个%s被后面元组中的字符串“Tom”和数字20替换。
%s表示使用str()函数将相应的数据进行转换。上面的例子中,20是十进制整数,它也可以使用%d进行占位:

占位符还可以是一个表示宽度的数字:

第一个%10s表示后面元组中的“name”字符将占据10个字符的宽度,因为“name”的宽度是4,那么需要在它前面补上6个空格。
%s中间的数字,正数表示右对齐,采用负数可以实现左对齐:

浮点数使用%f:

以八进制数进行输出:

以十六进制数进行输出:

使用%%输出百分号:

2.2.7 利用原始字符串表达字面本身的含义
如果你正在使用Windows系统编写程序,很可能会需要定义一个路径,就像这样的:

接下来我们用print语句进行输出:

你没有看错,就是这样的!为什么呢?因为\t将会变成Tab键,而\n会被翻译成回车。因此,路径就不得不这么书写:

现在好了,Windows系统的路径不再出现错误,两个反斜线表示一个真正的反斜线,它不会再和后面的字母t和n组合起来表示其他含义。不过,这种写法很麻烦,每次都要写两个反斜线,这个时候,原始字符串就派上用场了。
原始字符串就是在字符串前面加一个r而已:

有了原始字符串,路径看上去就真的是一个Windows路径了,不再显得那么奇怪。那么,原始字符串是怎么办到的呢?print打印出来的内容是方便给人看的,如果不用print,则Python交互解释器就会显示出它在内部存储的真正的样子:

原来是加上r后,Python自动把一个反斜线变成两个了!