What are the common methods for python string slicing?

WBOY
Release: 2023-04-18 18:40:03
forward
7984 people have browsed it

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
Copy after login

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
Copy after login

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!****
Copy after login

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
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!