Home >Backend Development >Python Tutorial >What are the common methods for python string 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
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
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)
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
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!