1. Slicing
Slicing: refers to the operation of intercepting a part of the operation object. Strings, lists, and tuples all support slicing operations
Syntax: Sequence [start position subscript: end position subscript: step size], does not include the end position subscript data, the step size is the selection interval, either positive or negative, the default is 1
Examples are as follows:
str = 'abcdefg_a' print(str[1:6:2], str[2:6], str[:3], str[3:], str[:]) print(str[::2], str[:-2], str[-6:-2], str[::-2], str[::-1]) print(str[-2:], str[2:-2], str[-2::-2], str[:-2:2], str[2:-2:2]) 输出: bdf cdef abc defg_a abcdefg_a acega abcdefg defg ageca a_gfedcba _a cdefg _fdb aceg ceg
2. Commonly used methods
2.1 Search
Search for a string: That is, find the substring in the character The position in the string or the number of occurrences
find():Detect whether a certain string is included in a certain string, and if it exists, return the substring The starting position subscript of the string, otherwise returns -1
Syntax: String sequence.find(substring, starting position subscript, End position subscript)
#index(): Detect whether a substring is included in a string, and if it exists, return the substring below the start position mark, otherwisereport an exception
Syntax: String sequence.index(substring, start position subscript, end position Subscript)
rfind(): has the same function as find(), but the search direction starts from the right, that is, the last occurrence position of the substring is returned.
rindex(): has the same function as index(), but the search direction starts from the right, that is, the last occurrence position of the substring is returned
count(): Returns the number of times a certain substring appears in the string
For example:
str = 'abcdefg_a' print('-------------------查找-------------------') print(str.find('c'), str.find('fg', 2, ), str.find('a', 2), str.find('h')) print(str.index('c'), str.index('fg', 2, ), str.index('a', 2)) print(str.find('a'), str.rfind('a'), str.index('a'), str.rindex('a'), str.count('a')) print(str.index('h')) 输出: -------------------查找------------------- 2 5 8 -1 2 5 8 0 8 0 8 2 ValueError: substring not found
2.2 Modify
Modify string:Modify the data in the string through function form
replace(): Replace
Syntax: String sequence.replace(old substring, new substring, maximum number of replacements)
split (): Split the string according to the specified characters
-
Syntax: String sequence.split (split characters, number of splits) # The number of data returned is the number of splits 1
join(): Combine strings with one character or substring, that is, merge multiple strings into a new string
-
Syntax: character or substring.join (sequence composed of multiple strings)
capitalize(): Convert the first character of the string to uppercase, convert Only the first character is capitalized, and the rest are lowercase
Syntax: String sequence.capitalize()
title( ): Convert the first letter of each word in the string to uppercase
lower(): Convert the uppercase letters in the string to lowercase
upper( ): Convert the string from lower case to upper case
swapcase(): Convert the string from upper to lower case
partition('separator') : Split the string according to the specified delimiter and return a triplet, consisting of left substring, delimiter, and right substring
min(str): Returns the string str Minimum letters
max(str): Returns the maximum letter
zfill(width): Outputs characters with a specified length of width String, right-aligned, with 0s added in front if the length exceeds the specified length.
lstrip(): Delete the space characters on the left side of the string
rstrip(): Delete space characters on the right side of the string
strip(): Delete space characters on both sides of the string
ljust() : The string is left-aligned and padded to the corresponding length with specified characters (default spaces)
Syntax: String sequence.ljust(length, padding character)
rjust(): The string is right-aligned and filled with specified characters (default spaces) to the corresponding length
Syntax: String sequence .rjust (length, padding characters)
- ##center(): Center-aligned and filled with specified characters (default spaces) to the corresponding length
- Syntax: String sequence.center (length, padding character)
For example:
print('--------------修改--------------') str1 = 'hello python and hello IT and hello world and hello YX !' print(str1.replace('and','&&')) print(str1.split('and'), str1.split('and', 2)) l = ['Hello', 'world', '!'] t = ('Hello', 'python', '!') print('_'.join(l), ' '.join(t)) # 用下划线_和空格连接 print(str1.capitalize()) # 首字符转为大写,其余均小写 print(str1.title()) # 每个单词首字母转为大写 str2 = ' Hello World ! ' print(str2.lower(), str2.upper(), str2.swapcase()) # 大写转小写,小写转大写,翻转大小写 print(str2.partition('rl'), str2.partition('o')) # 根据指定分隔符将字符串分割,返回三元元组 print(min(str2), max(str2), ord(min(str2)), ord(max(str2))) # str2中最小为空格对应十进制32,最大为r对应114 print(str2.zfill(21)) # 输出指定长度为21的字符串,右对齐,不足前面补0,超出指定长度则原样输出 print(str2.lstrip(), str2.rstrip(), str2.strip()) # 清除字符串左、右、两边空格字符 str3 = 'hello!' print(str3.ljust(13, '*'), str3.rjust(13, '*'), str3.center(14, '*')) 输出: --------------修改-------------- hello python && hello IT && hello world && hello YX ! ['hello python ', ' hello IT ', ' hello world ', ' hello YX !'] ['hello python ', ' hello IT ', ' hello world and hello YX !'] Hello_world_! Hello python ! Hello python and hello it and hello world and hello yx ! Hello Python And Hello It And Hello World And Hello Yx ! hello world ! HELLO WORLD ! hELLO wORLD ! (' Hello Wo', 'rl', 'd ! ') (' Hell', 'o', ' World ! ') r 32 114 00 Hello World ! Hello World ! Hello World ! Hello World ! hello!******* *******hello! ****hello!****2.3 Judgment
- startswith(): Check whether the string starts with the specified substring, if it returns True, otherwise it returns False, and sets the start and end position subscripts, which are within the specified range Check
- Syntax: string sequence.startswith(substring, start position subscript, end position subscript)
- endswith(): Checks whether the string ends with the specified substring, returns True, otherwise returns False, sets the start and end position subscripts, and checks within the specified range
- Syntax: String sequence.endswith (substring, starting position subscript, ending position subscript)
- isalpha(): If the string has at least one If the character and all characters are letters, it returns True, otherwise it returns False
- isdigit(): If the string only contains numbers, it returns True, otherwise it returns False
isalnum():若字符串至少有一个字符且所有字符都是字母或数字则返回True,否则返回False
isspace():若字符串只包含空格,则返回True,否则返回False
举例如下:
print('---------------判断----------------') str3 = 'hello!' print(str3.startswith('he'), str3.startswith('she'), str3.startswith('he',2,)) print(str3.endswith('!'), str3.endswith('。'), str3.endswith('!', 2, 5)) print(str3.isalpha(),str3.isalnum(), str3.isdigit(), str3.isspace()) 输出: ---------------判断---------------- True False False True False False False False False False
The above is the detailed content of What are the common methods for python string slicing?. For more information, please follow other related articles on the PHP Chinese website!

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

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.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft