


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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
