Home > Backend Development > Python Tutorial > How to intercept a string and obtain a substring

How to intercept a string and obtain a substring

anonymity
Release: 2019-05-25 10:56:50
Original
5781 people have browsed it

For example, if there is a string, python, how to get the first 3 digits, or the last 2 digits. Record it here.

How to intercept a string and obtain a substring

Operation process:

1. Obtain the substring in the string by using separators and subscripts

>>> text = 'python'
>>> text[0-2]   #使用 - 这种方式发现并没有获取想要的
'o'
>>> text[0:2]   #使用冒号 : 分割符,获取位置0到位置2,但是不包括位置2的字符,即 p y 0位置,1位置
'py'
>>> text[3:4]   #获取位置3,4,但是不包括位置4,那么只是去位置3上的字符
'h'
>>> text[2:5]   #获取2,3,4位置上的字符
'tho
Copy after login

Remarks: Always include the starting position and always exclude characters at the end position. n:m includes the n position, but does not include the m position.

2. The default value of the subscript.

>>> text[:2]   #如果冒号左边没有值,就是从0开始,即省略了第一个值,默认是0,就是0:2
'py'
>>> text[2:]   #2:从2开始,一直到结束,省略冒号后面的索引值,就是这个字符串的长度,python长度是6,就是2:6
'thon'
>>> text[:2] + text[2:]  #[:2] + [2:] 就是整个字符
'python'
>>> text[-2:]   #备注:这个是从倒数第2个字符到结尾。
'on'
>>> text[-4:]   #从倒数第4个字符到结尾
'thon'
Copy after login

Note: The subscript has a default value.

3. What to do if the subscript exceeds the range when using splitting

>>> text[3:40]  #如果结束的下标,超过了范围,那么自动到字符串结尾
'hon'
>>> text[21:]   #如果开始的下标都超过了字符串长度,那么就是返回空字符串
''
>>> text[21:2]  #同样,开头的下标超过了字符串长度,结束下标就不看了,也没有报错,而是返回空字符串
''
Copy after login

The above is the detailed content of How to intercept a string and obtain a substring. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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