Home > Backend Development > Python Tutorial > How to get a substring of a string

How to get a substring of a string

anonymity
Release: 2019-05-25 09:47:40
Original
4089 people have browsed it

String is the most commonly used data type in Python. We can use quotes (' or ") to create strings.

Creating a string is as simple as assigning a value to a variable.

For example: var1 = 'Hello World!'

How to get a substring of a string

Code example:

str = ‘0123456789’
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取
Copy after login

Result:

012
0123456789
6789
0123456
2
9
9876543210
78
789
96
Copy after login

The above is the detailed content of How to get a substring of a string. 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