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!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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