Home >Backend Development >Python Tutorial >Share a summary of functions and methods commonly used to manipulate strings in Python
This article mainly shares a summary of the functions and methods of string commonly used in Python, including the formatted output of strings and splicing and other basic knowledge, friends who need it can refer to
For example, such a string Python, it is just a few characters: P, y, t, h, o, n, arranged. This arrangement is very strict, not only the characters themselves, but also the order. In other words, if a certain character is changed, a new string will be programmed; if the order of these characters changes, it will also become a new character. string.
In Python, objecttypes like strings (other similar object types with this characteristic will appear later, such as lists) are collectively called sequences. As the name suggests, a sequence is an "orderly arrangement."
For example, the 108 heroes in Shuibo Liangshan (there are obviously women among them, do the female men come from here?), is an "orderly arrangement" sequence. Ranked from the eldest, Song Jiang, to the 108th golden retriever, Duan Jingzhu. In this sequence, each person has a number, and the number corresponds to each person one-to-one. No. 1 is Song Jiang and No. 2 is Lu Junyi. In turn, through each person's name, his corresponding number can also be found. What is Wu Song's number? No. 14. Where is Li Kui? number 22.
In Python, these numbers are given an elegant name, called index (Other programming languages also call it this way, and it is not unique to Python.) .
Indexing and slicing
The index was explained using the example of Liangshan Hero. Let’s look at the example in Python:
>>> lang = "study Python" >>> lang[0] 's' >>> lang[1] 't'
There is a string assigned to the variable through an assignment statement lang. If you want to get the first word s of this string, you can use lang[0]. Of course, if you don't want to let the variable lang point to that string through an assignment statement, you can also do this:
>>> "study Python"[0] 's'
Effect it's the same. Because lang is a label, it points to the "study Python" string. When asking Python to execute lang[0], it is to go to that string object, just like the above operation. However, if you don't use a variable like lang, it will take a lot of time to write it again later. You have to write the entire string every time. To save trouble, copy it to a variable. Variables are representations of strings.
The sorting method of this sequence of strings is a little different from that of Liangshan Heroes. The first one is not represented by the number 1, but by the number 0. Not just Python, many other languages sort starting from 0. Why do this? That's the rule. Of course, this provision has certain advantages. I won’t go into details here. If you are interested, go to Google and find an article specifically explaining this.
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
---|---|---|---|---|---|---|---|---|---|---|---|
t | u | d | y | l | p | y | t | h | o | n |
占位符 | 说明 |
---|---|
%s | 字符串(采用 str()的显示) |
%r | 字符串(采用 repr()的显示) |
%c | 单个字符 |
%b | 二进制整数 |
%d | 十进制整数 |
%i | 十进制整数 |
%o | 八进制整数 |
%x | 十六进制整数 |
%e | 指数 (基底写为 e) |
%E | 指数 (基底写为 E) |
%f | 浮点数 |
%F | 浮点数,与上相同 |
%g | 指数(e) 或浮点数 (根据显示长度) |
%G | 指数(E)或浮点数 (根据显示长度) |
看例子:
>>> a = "%d years" % 15 >>> print a 15 years
当然,还可以在一个字符串中设置多个占位符,就像下面一样
>>> print "Suzhou is more than %d years. %s lives in here." % (2500, "qiwsir") Suzhou is more than 2500 years. qiwsir lives in here.
对于浮点数字的打印输出,还可以限定输出的小数位数和其它样式。
>>> print "Today's temperature is %.2f" % 12.235 Today's temperature is 12.23 >>> print "Today's temperature is %+.2f" % 12.235 Today's temperature is +12.23
注意,上面的例子中,没有实现四舍五入的操作。只是截取。
常用的字符串方法
字符串的方法很多。可以通过 dir 来查看:
>>> dir(str) ['add', 'class', 'contains', 'delattr', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'getnewargs', 'getslice', 'gt', 'hash', 'init', 'le', 'len', 'lt', 'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmod', 'rmul', 'setattr', 'sizeof', 'str', 'subclasshook', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
这么多,不会一一介绍,要了解某个具体的含义和使用方法,最好是使用 help 查看。举例:
>>> help(str.isalpha)
Help on method_descriptor: isalpha(...) S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
按照这里的说明,就可以在交互模式下进行实验。
>>> "python".isalpha() # 字符串全是字母,应该返回 True True >>> "2python".isalpha() # 字符串含非字母,返回 False False
split
这个函数的作用是将字符串根据某个分割符进行分割。
>>> a = "I LOVE PYTHON" >>> a.split(" ") ['I', 'LOVE', 'PYTHON']
这是用空格作为分割,得到了一个名字叫做列表(list)的返回值,关于列表的内容,后续会介绍。还能用别的分隔吗?
>>> b = "www.itdiffer.com" >>> b.split(".") ['www', 'itdiffer', 'com']
去掉字符串两头的空格
这个功能,在让用户输入一些信息的时候非常有用。有的朋友喜欢输入结束的时候敲击空格,比如让他输入自己的名字,输完了,他来个空格。有的则喜欢先加一个空格,总做的输入的第一个字前面应该空两个格。
这些空格是没用的。Python 考虑到有不少人可能有这个习惯,因此就帮助程序员把这些空格去掉。
方法是:
S.strip() 去掉字符串的左右空格
S.lstrip() 去掉字符串的左边空格
S.rstrip() 去掉字符串的右边空格
例如:
>>> b=" hello " # 两边有空格 >>> b.strip() 'hello' >>> b ' hello '
特别注意,原来的值没有变化,而是新返回了一个结果。
>>> b.lstrip() # 去掉左边的空格 'hello ' >>> b.rstrip() # 去掉右边的空格 ' hello'
字符大小写的转换
对于英文,有时候要用到大小写转换。最有名驼峰命名,里面就有一些大写和小写的参合。如果有兴趣,可以来这里看自动将字符串转化为驼峰命名形式的方法。
在 Python 中有下面一堆内建函数,用来实现各种类型的大小写转化
S.upper() #S 中的字母大写
S.lower() #S 中的字母小写
S.capitalize() # 首字母大写
S.isupper() #S 中的字母是否全是大写
S.islower() #S 中的字母是否全是小写
S.istitle()
看例子:
>>> a = "qiwsir,Python" >>> a.upper() # 将小写字母完全变成大写字母 'QIWSIR,PYTHON' >>> a # 原数据对象并没有改变 'qiwsir,Python' >>> b = a.upper() >>> b 'QIWSIR,PYTHON' >>> c = b.lower() # 将所有的小写字母变成大写字母 >>> c 'qiwsir,Python' >>> a 'qiwsir,Python' >>> a.capitalize() # 把字符串的第一个字母变成大写 'Qiwsir,Python' >>> a # 原数据对象没有改变 'qiwsir,Python' >>> b = a.capitalize() # 新建立了一个 >>> b 'Qiwsir,Python' >>> a = "qiwsir,github" # 这里的问题就是网友白羽毛指出的,非常感谢他。 >>> a.istitle() False >>> a = "QIWSIR" # 当全是大写的时候,返回 False >>> a.istitle() False >>> a = "qIWSIR" >>> a.istitle() False >>> a = "Qiwsir,github" # 如果这样,也返回 False >>> a.istitle() False >>> a = "Qiwsir" # 这样是 True >>> a.istitle() True >>> a = 'Qiwsir,Github' # 这样也是 True >>> a.istitle() True >>> a = "Qiwsir" >>> a.isupper() False >>> a.upper().isupper() True >>> a.islower() False >>> a.lower().islower() True
再探究一下,可以这么做:
>>> a = "This is a Book" >>> a.istitle() False >>> b = a.title() # 这样就把所有单词的第一个字母转化为大写 >>> b 'This Is A Book' >>> b.istitle() # 判断每个单词的第一个字母是否为大写 True
join 拼接字符串
用“+”能够拼接字符串,但不是什么情况下都能够如愿的。比如,将列表(关于列表,后续详细说,它是另外一种类型)中的每个字符(串)元素拼接成一个字符串,并且用某个符号连接,如果用“+”,就比较麻烦了(是能够实现的,麻烦)。
用字符串的 join 就比较容易实现。
>>> b 'www.itdiffer.com' >>> c = b.split(".") >>> c ['www', 'itdiffer', 'com'] >>> ".".join(c) 'www.itdiffer.com' >>> "*".join(c) 'www*itdiffer*com'
这种拼接,是不是简单呢?
The above is the detailed content of Share a summary of functions and methods commonly used to manipulate strings in Python. For more information, please follow other related articles on the PHP Chinese website!