2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Table of contents
Chapter 6 String Objects and Slice Operations
6.2 Common methods used in characters
String: A string consisting of multiple characters
Characters: symbols visible to the naked eye
Byte: Invisible to the naked eye
Python defines strings in the following way:
single quote double quote triple quote str()
>>> dir(s) ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
capitalize ------- Capitalize the first letter in a string
>>> s 'this is a string' >>> s.capitalize() 'This is a string'
center(width, fillchar=' ') ------ Display the string in the center according to the given length, aligning it in the center
rjust --------- right alignment
ljust ------ left alignment
>>> help(s.center) Help on built-in function center: center(width, fillchar=' ', /) method of builtins.str instance Return a centered string of length width. Padding is done using the specified fill character (default is a space). >>> s.center(40) ' this is a string ' >>> s.center(40,"*") '************this is a string************' >>> s.rjust(40) ' this is a string' >>> s.ljust(40) 'this is a string ' >>> s.ljust(40,"*") 'this is a string************************' >>> s.rjust(40,"*") '************************this is a string'
count --------- The number of times the character appears in the string
>>> s 'this is a string' >>> s.count("s") 3 >>> s.count("is") 2
endswith ------- Determine whether the string ends with XXX
startswith ------- Determine whether the string starts with XXX
>>> s.endswith("g") True >>> s.endswith("ing") True >>> s.endswith("f") False >>> s.startswith("t") True >>> s.startswith("f") False
index ------ The position of the first occurrence of the character or string being searched in the string. If it does not exist, an exception is thrown (error)
rindex -------Search from right to left, the position of the first occurrence of the character or string in the string (equivalent to the position of the last occurrence of the character or string in the string from left to right), if it does not exist, an exception is thrown (error)
>>> s 'this is a string' >>> s.index("s") 3 >>> s.index("is") 2 >>> s.index("f") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> s.index(" ") 4 >>> s.rindex("s") 10 >>> s.rindex("f") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
find ------- The first position of the character or string to be found in the string. If it does not exist, it returns -1
rfind-----Search from right to left, the position of the first occurrence of the character or string in the string (equivalent to the position of the last occurrence of the character or string in the string from left to right), if it does not exist, return -1
>>> s 'this is a string' >>> s.find("s") 3 >>> s.find("f") -1 >>> s.rfind("f") -1 >>> s.rfind("s") 10
encode ----- Python 3 method for converting strings to bytes, decode() method for converting bytes to strings (method in bytes)
>>> s 'this is a string' >>> s.encode() b'this is a string' >>> d = s.encode() >>> d b'this is a string' >>> type(d) <class 'bytes'> >>> d b'this is a string' >>> d.decode() 'this is a string' >>> ss = d.decode() >>> ss 'this is a string' >>> type(ss) <class 'str'>
format ------ format string, concatenate string
isupper ------ Checks whether the string is all uppercase letters
islower ----- ------ Determines whether the string is all lowercase letters
>>> s.isupper() False >>> s.islower() False
istitle ----- Determine whether it is a title
>>> s.istitle() False >>> ss = "This Is A Dog" >>> ss.istitle() True
isspace ----- Determines whether it is a space. Not commonly used
>>> sss = " " >>> sss.isspace() True >>> ss 'This Is A Dog' >>> ss.isspace() False
isdigit ------ Determine whether it is a number
>>> sss = "123234344" >>> sss.isdigit() True >>> ss 'This Is A Dog' >>> ss.isdigit() False >>> sss = "1233443gggg" >>> sss.isdigit() False
isalnum ------ determines whether it is a letter or a number (alpha-numeric)
>>> help(s.isalnum) Help on built-in function isalnum: isalnum() method of builtins.str instance Return True if the string is an alpha-numeric string, False otherwise. A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string. >>> sss '1233443gggg' >>> sss.isalnum() True >>> ss 'This Is A Dog' >>> ss.isalnum() False
isalpha ------ determines whether it is a letter
title ----- Converts a string to the format of a title
>>> s 'This is a string' >>> s.istitle() False >>> s.title() 'This Is A String' >>> sss = s.title() >>> sss 'This Is A String' >>> sss.istitle() True
upper ------- Converts a string to upper case
lower ------- Convert a string to lowercase
>>> s 'This is a string' >>> s.lower() 'this is a string' >>> s.upper() 'THIS IS A STRING'
split ----- Split the string according to the specified symbol, and the return value is a list
>>> s 'This is a string' >>> s.split(" ") ['This', 'is', 'a', 'string'] >>> l = s.split(" ") >>> l ['This', 'is', 'a', 'string'] >>> type(l) <class 'list'> >>> l = s.split("s") >>> l ['Thi', ' i', ' a ', 'tring']
join ------ concatenates an iterable object into a string according to the specified format
>>> ls = ["A","B","c","d"] >>> type(ls) <class 'list'> >>> ss = " ".join(ls) >>> ss 'A B c d' >>> type(ss) <class 'str'> >>> ss = "*".join(ls) >>> ss 'A*B*c*d'
strip ------- Clear spaces on both sides
rstrip------ Clear spaces on the right
lstrip -------- Clear the left space
>>> ss = " hhhhhhh " >>> ss ' hhhhhhh ' >>> ss.strip() 'hhhhhhh' >>> ss.strip() 'hhhhhhh' >>> ss ' hhhhhhh ' >>> ss.rstrip() ' hhhhhhh' >>> ss.lstrip() 'hhhhhhh '
replace ("original character", "new character") ------ replace the corresponding character
>>> s 'This is a string' >>> s.replace("s","t") 'Thit it a ttring'
Slices: used to separate iterable objects (containers)
Syntax rules:
object[start_index:end_index:step]
start_index ------- Starting index (starting position)
end_index ------ End index (end position), does not include the value at end_index
step ---- step length, can be positive or negative, positive (from left to right) or negative (from right to left), the default value is 1
object[:] ----- 切割的是一个完整的对象 object[start_index:] ------ 从start_index开始切割到最后的位置,步长为1 object[:end_index] ------ 从最开始的位置切割到end_index处,但是不包含end_index object[start_index:end_index] ------- 从start_index开始切割到end_index处,但是不包含end_index,步长为1 object[start_index:end_index:step] ------------ 从start_index开始切割到end_index处,但是不包含end_index,步长为step
The interval that is closed at the beginning and opened at the end
ls = [0,1,2,3,4,5,6,7,8,9]
1. Cut a single value
>>> ls [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[0] 0 >>> ls[-4] 6
2. Cutting complete objects
>>> ls[:] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[::] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[::-1] #-1 表示从右往左切割 所以是倒序 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
3. Both start_index and end_index are positive numbers
>>> ls [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[1:6] [1, 2, 3, 4, 5] >>> ls[1:6:-1] # start_index=1 end_index = 6表示的是从1切割到6的位置,但是不包含6处的值,从左往右切割,step=-1 表示从右往左 [] >>> ls[6:1] [] >>> ls[6:1:-1] [6, 5, 4, 3, 2] >>> ls[:6] [0, 1, 2, 3, 4, 5] >>> ls[:6:-1] [9, 8, 7] >>> ls[6:] [6, 7, 8, 9] >>> ls[6::-1] [6, 5, 4, 3, 2, 1, 0] >>>
4. Both start_index and end_index are negative
>>> ls [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[-1:-6] [] >>> ls[-1:-6:-1] [9, 8, 7, 6, 5] >>> ls[-6:-1] [4, 5, 6, 7, 8] >>> ls[:-6] [0, 1, 2, 3] >>> ls[:-6:-1] [9, 8, 7, 6, 5] >>> ls[-6:] [4, 5, 6, 7, 8, 9] >>> ls[-6::-1] [4, 3, 2, 1, 0]
5. Start_index and end_index positive and negative combination
>>> ls [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[1:-6] [1, 2, 3] >>> ls[1:-6:-1] [] >>> ls[-1:6] [] >>> ls[-1:6:-1] [9, 8, 7]
6. Serial sectioning
>>> ls [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[:8][2:5][-1:] [4] ls[:8] ----- [0,1,2,3,4,5,6,7] ls[:8][2:5] ----- [2,3,4] ls[:8][2:5][-1:] ----- [4]
7. The three parameters of the slice can also be expressions
>>> ls [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> ls[2+1:3*2:7%3] [3, 4, 5] >>> ls[3:6:1] [3, 4, 5] >>> ls[2:6:2] [2, 4]
8. Slicing can also cut other objects
>>> (1,2,3,4,5,6,7,8,9)[:3] (1, 2, 3) >>> "ABCDEFGHIJK"[::2] 'ACEGIK' >>> for i in range(1,100)[2::3][-10:]: ... print(i) ... 72 75 78 81 84 87 90 93 96 99
Interview questions:
1. If the data is cut by slicing and exceeds the subscript range, will an error be reported?
No error will be reported. If it exceeds the range, the complete object will be returned. If there is a contradiction, [] will be returned.
2. How to output a list in reverse order in Python?
Cycle Reverse
[::-1]
list.reverse()