Table of Contents
1. Slicing
2. Commonly used methods
2.1 Search
2.2 Modify
Home Backend Development Python Tutorial What are the common methods for python string slicing?

What are the common methods for python string slicing?

Apr 18, 2023 pm 06:40 PM
python

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

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles