Home >Backend Development >Python Tutorial >How to extract characters from a string in python

How to extract characters from a string in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-21 14:50:1549324browse

String interception, also called string slicing, uses square brackets [ ] to intercept strings. In Python, a single character is also used as a string.

String [start index: end index: step size]

Start index: start interception from the specified position;

End index: end interception from the specified position, but not Contains the characters at that position.

Step size: When not specified, the step size is 1;

String [start index: end index]

How to extract characters from a string in python

First we understand Next, there are two indexing methods for strings in Python, as shown below:

How to extract characters from a string in python

Positive index means indexing from front to back, starting from 0 by default; negative index means Index from back to front; the index value can also be called a subscript. Example code:

How to extract characters from a string in python

String interception follows the principle of "left-closed, right-open", also called "left-inclusive" Package right":

[Start subscript: Start subscript)

Related recommendations: "Python Video Tutorial"

There are two indexing methods There are two interception methods. Example code:

How to extract characters from a string in python

Because it involves execution efficiency issues, you need to flexibly use these two index methods to intercept strings according to the situation, such as : If you want to quickly get the last part of the string, using negative index is the fastest.

>>> str='0123456789'
>>> print(str[0:3])#截取第一位到第三位的字符
012
>>> print(str[:])#截取字符串的全部字符
0123456789
>>> print(str[6:])#截取第七个字符到结尾
6789
>>> print(str[:-3])#截取从头开始到倒数第三个字符之前
0123456
>>> print(str[2])#截取第三个字符
2
>>> print(str[-1])#截取倒数第一个字符
9
>>> print(str[::-1])#创造一个与原字符串顺序相反的字符串
9876543210
>>> print(str[-3:-1])#截取倒数第三位与倒数第一位之前的字符
78
>>> print(str[-3:]) #截取倒数第三位到结尾
789
>>> print(str[:-5:-3])#逆序截取
96

The above is the detailed content of How to extract characters from a string in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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