"Learning Python with You Hand in Hand" 10-String Functions

In the previous article "Learning Python with You Hand in Hand" 9-string operations , we learned a variety of string operations, which deepened our understanding of strings and facilitated our operations on strings .

In this article, I will introduce several functions related to strings, which are very helpful for us to use strings flexibly and improve string manipulation capabilities.

​Although the title of this article is called string functions, strictly speaking, the content of this article is not all functions, most of which should be called methods.

There are actually only three functions in the following table, namely len(string), max(string), min(string). When a function is called, write the object in parentheses, just like len(string) writes string in parentheses.

When the method is called, the object must be written in front, then a "." is added, and then the name of the method is written. Just like string.upper().

The reason why this is explained first is that this kind of formal difference will appear when we introduce later, in order to avoid any doubts at the time, we will explain it first.

At present, we only need to know the difference in form. As for why there is such a difference, I will introduce it to you in the future.

For convenience, in this article, we will first call them "functions". You can learn about what operations on strings can be implemented by each function based on their role.

Serial number

function

effect

1

capitalize()

Convert the first character of the string to uppercase

2

center(width, fillchar)

Returns a string with the specified width in the center, fillchar is the filled character, and the default is a space.

3

count(str, beg= 0,end=len(string))

Returns the number of occurrences of str in string, if beg or end is specified, returns the number of occurrences of str in the specified range

4

bytes.decode(encoding="utf-8", errors="strict")

There is no decode method in Python3, but we can use the decode() method of the bytes object to decode a given bytes object, which can be encoded and returned by str.encode().

5

encode(encoding='UTF-8',errors='strict')

Encode the string in the encoding format specified by encoding. If an error occurs, a ValueError will be reported by default, unless errors specify'ignore' or'replace'

6

endswith(suffix, beg=0, end=len(string))

Check whether the string ends with obj, if beg or end is specified, check whether the specified range ends with obj, if yes, return True, otherwise return False.

7

expandtabs(tabsize=8)

Convert the tab symbol in the string to a space. The default number of spaces for the tab symbol is 8.

8

find(str, beg=0, end=len(string))

Check if str is contained in the string, if the range beg and end are specified, check if it is contained within the specified range, if it contains, return the starting index value, otherwise return -1

9

index(str, beg=0, end=len(string))

Same as the find() method, except that an exception will be reported if str is not in the string.

10

isalnum ()

If the string has at least one character and all characters are letters or numbers, it returns True, otherwise it returns False

11

isalpha ()

If the string has at least one character and all characters are letters, it returns True, otherwise it returns False

12

isdigit()

If the string contains only numbers, it returns True, otherwise it returns False.

13

islower()

If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, return True, otherwise return False

14

isnumeric()

If the string contains only numeric characters, it returns True, otherwise it returns False

15

isspace()

If the string contains only blanks, it returns True, otherwise it returns False.

16

list ()

i If the string is titled (see title()), return True, otherwise return False

17

isupper()

If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase, return True, otherwise return False

18

join(seq)

Use the specified string as the delimiter to merge all the elements (the string representation) in seq into a new string

19

len (string)

Return string length

20

light (width [, fillchar])

Return a new string with the original string left-aligned and filled to the length width with fillchar. The fillchar defaults to spaces.

21

lower()

Convert all uppercase characters in the string to lowercase.

22

lstrip()

Truncate the spaces or specified characters on the left side of the string.

23

maketrans()

Create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string, which represents the character to be converted, and the second parameter is also a string that represents the target of the conversion.

24

max(str)

Returns the largest letter in the string str.

25

min (str)

Returns the smallest letter in the string str.

26

replace(old, new [, max])

Replace str1 in the string with str2. If max is specified, the replacement will not exceed max times.

27

rfind(str, beg=0,end=len(string))

It is similar to the find() function, but searches from the right.

28

rindex( str, beg=0, end=len(string))

Similar to index(), but starts from the right.

29

rjust(width,[, fillchar])

Return a new string with the original string right-aligned and filled with fillchar (default space) to the length width

30

rstrip()

Remove the spaces at the end of the string string.

31

split(str="", num=string.count(str))

num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串

32

splitlines([keepends])

按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

33

startswith(substr, beg=0,end=len(string))

检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。

34

strip([chars])

在字符串上执行 lstrip()和 rstrip()

35

swapcase()

将字符串中大写转换为小写,小写转换为大写

36

title()

返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())

37

translate(table, deletechars="")

根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中

38

upper()

转换字符串中的小写字母为大写

39

zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

40

isdecimal()

检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。

以上表格及其内容来源于菜鸟教程(https://www.runoob.com/),在需要的时候,可以查看函数的具体使用方法。

下面就几个常用的字符串函数进行具体的讲解。

1、split()

把split()函数放在第一位,自然说明它非常有用了。它的作用是将字符串按照某个指定的字符进行分割。

split()函数有两个参数,分别是str和num。

string.split(str="", num=string.count(str))

str是分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

num是分隔次数,按照分隔符从左往右根据分割次数进行分割,默认是全部分割。

最前面的string代表需要被分割的字符串。使用string.split(),代表对string调用split()函数。

In [1]: a = "Life is short, you need Python."
​
In [2]: a.split()   # 对全部分隔符进行分割
Out[2]: ['Life', 'is', 'short,', 'you', 'need', 'Python.']
​
In [3]: a.split(' ', 2)   # 只对前两个空格进行分割
Out[3]: ['Life', 'is', 'short, you need Python.']
​
In [4]: a.split(2)   # 指定分割次数时必须指定分割符,只写分割次数会报错 
Out[4]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-7-c72104ee958b> in <module>
        ----> 1 a.split(2)   # 指定分割次数时必须指定分割符,只写分割次数会报错
        
        TypeError: must be str or None, not int
​
In [5]: a.split('o')   # 但可以只指定分隔符,分割次数为默认全部分割
Out[5]: ['Life is sh', 'rt, y', 'u need Pyth', 'n.']
​
In [6]: a.split('or')   # 也可以指定字符串作为分隔符
Out[6]: ['Life is sh', 't, you need Python.']

根据注释内容,相信大家对分割的过程都不会有什么疑惑,但是对于分割的结果为什么是用方括号[]括起来的,可能会存在疑问。其实,这种用方括号[]括起来的形式就是我们后面要讲到的列表,是一种非常非常重要而且常用的数据结构。

前面之所以说split()函数重要,并且把它放在第一个讲,就是因为我们后面会经常用它来构建列表。

现在大家可以先不用对列表这种形式关注太多,只需要知道字符串经过分隔后形成的多个字符串,都放在一个列表里就可以了。

另外,细心的朋友可能会发现,在我们上面的例子中,一直都在对a进行分割。难道在多次分割的过程中a都没有变化吗?

答案是:是的。

虽然我们一直在对a调用split()函数,其实并不是真的在对a进行分割,只是对a的一个镜像进行分割,a本身并没有被分割。

如果我们想保留分割的结果,就需要把分割后的结果,赋值给另外一个变量,当然这个变量也可以是a。

In [7]: a = "Life is short, you need Python."
        b = a.split()
In [8]: a
Out[8]: 'Life is short, you need Python.'
​
In [9]: b
Out[9]: ['Life', 'is', 'short,', 'you', 'need', 'Python.']
​
In [10]: a = "Life is short, you need Python."
         a = a.split()
         
In [11]: a
Out[11]: ['Life', 'is', 'short,', 'you', 'need', 'Python.']

 2、find()和index()

find()和index()都是检索函数,都是在字符串的指定范围内检索是否含有指定的字符。

如果检索值存在,就返回第一个符合要求的字符的位置(也就是我们在《手把手陪您学Python》7——字符串的索引中讲到的位置)。

它们的区别是,如果检索值不存在,find()会返回-1,而index()会报错。

string.find(str, beg=0, end=len(string))

string.index(str, beg=0, end=len(string))

和介绍split()函数时一样,所有的函数都是对string进行调用的,后面就不再重复了。

str是要检索的字符或者字符串。

beg和end分别是开始和结束的检索位置(位置的概念也都一样,下面也不重复了),默认是从0位置开始,从字符串的长度的位置,也就是末尾位置结束的。

In [12]: a = "Life is short, you need Python."
​
In [13]: a.find('i')   # 默认从头开始检索
Out[13]: 1
​
In [14]: a.find('i', 3, 8)   # 从位置3,也就是e,开始检索
Out[14]: 5
​
In [15]: a.index('is', 3, 8)   # 如果存在,返回也是检索值第一个字符所在的位置
Out[15]: 5
​
In [16]: a.find('w')   # find()不存在返回-1
Out[16]: -1
​
In [17]: a.index('w')   # index()不存在报错
Out[17]: ---------------------------------------------------------------------------
         ValueError                                Traceback (most recent call last)
         <ipython-input-25-f2bf832fc484> in <module>
         ----> 1 a.index('w')
         
         ValueError: substring not found

与find()和index()类似的还有rfind()和rindex()两个函数,只不过它们是从右边开始查找,大家可以自己试一下。

3、count()

count()是计数函数,返回的是字符串中包含指定字符的个数。

在讲解split()函数时,其实忽略了一个内容,就是函数完整描述中num=string.count(str)的含义。其实,它代表的就是string中str(分隔符)的数量。

count()函数的参数与find()、index()完全一样,这里就不再逐一讲解了。

string.count(str, beg= 0,end=len(string))

In [18]: a = "Life is short, you need Python."
​
In [19]: a.count('o')   # 默认从头开始计数
Out[19]: 3
​
In [20]: a.count('o', 10, 20)   # 写两个数字,分别代表开始和结束的位置 
Out[20]: 2
​
In [21]: a.count('o', 10)   # 只写一个数字,代表开始的位置,默认到句尾结束
Out[21]: 3
​
In [22]: a.count('o', 12, 15)   # 如果不存在,返回0
Out[22]: 0

4、len()

len()函数很简单,就是返回字符串的长度,没有其它的参数。但它的形式不是string.end(),而是

len(string)

len(string)就是我们最开始说的真正的“函数”,它的调用方法是将对象放在括号里。这是和我们刚才讲的string.split()、string.find()和string.count()不一样的地方,所以请大家注意。

在讲解find()和index()时也忽略了一个内容,就是end=len(string),代表结束的位置等于字符串的长度。

In [23]: a = "Life is short, you need Python."
         len(a)
Out[23]: 31

5、lstrip()、rstrip()和strip()

有时,在进行字符串的对比时,明明两个字符串一样,但进行比较时,却是不同的值。这是由于在数据保存、传输的过程中,可能前后都被加上了数量不等的空格。虽然两个字符串看上去一样,实际却是不同的。

lstrip()、rstrip()和strip()就是用来截取字符串开头或结尾处空格(或指定字符)的函数,可以把一些因为未知原因产生的垃圾字符删除,一般用于数据读取的清洗、整理。

string.lstrip(str)

用来截取掉字符串左边(开头)的指定字符(str默认为空格)。

string.rstrip(str)

用来截取掉字符串右边(结尾)的指定字符(str默认为空格)。

string.strip(str)

用来同时截取开头和结尾的指定字符(str默认为空格)。

In [24]: a = "   Life is short, you need Python.   "   # 字符串前后各加了三个空格
​
In [25]: a.lstrip()   # 左边的空格被截取,右边的空格被保留
Out[25]: 'Life is short, you need Python.   '
​
In [26]: a.rstrip()   # 右边的空格被截取,左边的空格被保留
Out[26]: '   Life is short, you need Python.'
​
In [27]: a.strip()   # 左右两边的空格都被截取
Out[27]: 'Life is short, you need Python.'
​
In [28]: a = "abcLife is short, you need Python.abc"   # 字符串前后各加了一个abc
​
In [29]: a.lstrip('abc')   # 左边的abc被截取,右边的abc被保留
Out[29]:  'Life is short, you need Python.abc'
​
In [30]: a.rstrip('abc')   # 右边的abc被截取,左边的abc被保留
Out[30]: 'abcLife is short, you need Python.'
​
In [31]: a.strip('abc')   # 左右两边的abc都被截取
Out[31]: 'Life is short, you need Python.'
​
In [32]: a.strip('c')   # 只有右边是以c结尾的,所以截取了右边的c 
Out[32]: 'abcLife is short, you need Python.ab'

6、判断函数

判断函数是指判断字符串是否都是字母isalpha(),是否值只包含数字字符isnumeric(),是否都是小写字母islower()等等表示判断的函数,也就是在上面函数列表中以is开头的几个函数。

如果结果为真,返回True;如果结果为假,返回False。所有判断语句的结果的返回值都是True或False的布尔值,后面也不再赘述了。

In [33]: a = "LifeisshortyouneedPython"
        a.isalpha()   # 是否只包含字母
Out[33]: Ture
​
In [34]: a = "Life is short, you need Python."
         a.isalpha()   # 因为包含空格和符号,所以返回False
Out[34]: True
​
In [35]: a = "3456789"
         a.isnumeric()   # 是否只包括数字字符
Out[35]: True
​
In [36]: a = "3456789"
         a.isdigit()   # 是否只包括数字
Out[36]: True
​
In [37]: a = "四六七八"
         a.isnumeric()   # 是否只包括数字字符,数字字符可以是阿拉伯数字、罗马数字、汉字数字
Out[37]: True
​
In [38]: a = "四六七八IV"
         a.isdigit()   # 是否只包括阿拉伯数字
Out[38]: False

7、字母处理

最后一类比较常用的字符串函数是用来对字母进行处理的,主要就是大小写的转换。

In [39]: a = 'python'
         a.capitalize()   # 可以使用变量,将第一个字符变为大写
Out[39]: 'Python'
​
In [40]: 'python'.capitalize()   # 也可以直接使用字符串
Out[40]: 'Python'
​
In [41]: capitalize('python')   # 但因为是“方法”,不能写成这样
Out[41]: ---------------------------------------------------------------------------
         NameError                                 Traceback (most recent calllast)
         <ipython-input-41-8d69b142f654> in <module>
         ----> 1 capitalize('python')   # 但因为是“方法”,不能写成这样
         
         NameError: name 'capitalize' is not defined
         
In [42]: a = 'PyThOn'
         a.lower()   # 将大写字母变为小写
Out[42]: 'python'
​
In [43]: a = 'PyThOn'
         a.lower()   # 将小写字母变为大写
Out[43]: 'python'
​
In [44]: a = 'PyThOn'
         a.swapcase()   # 大小写字母转换
Out[44]: 'pYtHoN'
​
In [45]: a = 'pYtHoN iS pErFecT!'
         a.title()   # 标题化——每个单词均以大写字母开头,其它为小写字母
Out[45]: 'Python Is Perfect!

今天,用了较长的篇幅给大家介绍了字符串函数的用法,再加上前面的索引、切片以及运算功能,大家就可以体会到Python对于字符串的强大的处理功能了。

下一篇,将给大家介绍字符串的格式化输出方法,也是有关字符串的最后一个主题,敬请关注。

 

 


感谢阅读本文!如有任何问题,欢迎留言,一起交流讨论^_^

欢迎扫描下方二维码,关注“亦说Python”公众号,阅读《手把手陪您学Python》系列文章的其他篇目,或点击下方链接直达。

《手把手陪您学Python》1——为什么要学Python?

《手把手陪您学Python》2——Python的安装

《手把手陪您学Python》3——PyCharm的安装和配置

《手把手陪您学Python》4——Hello World!

《手把手陪您学Python》5——Jupyter Notebook

《手把手陪您学Python》6——字符串的标识

《手把手陪您学Python》7——字符串的索引

《手把手陪您学Python》8——字符串的切片

《手把手陪您学Python》9——字符串的运算

For Fans:关注“亦说Python”公众号,回复“手10”,即可免费下载本篇文章所用示例语句。

亦说Python——Python爱好者的学习分享园地

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98756730