essentially , A string is made up of multiple characters , There is order between the characters , This sequence number is called the index (index).Python Allows single or multiple characters in a string to be manipulated by index , For example, get the character at the specified index , Returns the index value of the specified character, etc .
After knowing the string name , Square brackets [ ] The corresponding characters can be accessed by using the index in , The specific syntax format is :
strname[index]
strname Represents the string name ,index Indicates the index value .
Python Allows indexes to be used from both ends of a string :
Take a look at the following example to demonstrate :
url = 'http://c.biancheng.net/python/'
# Get the index as 10 The characters of
print(url[10])
# Get the index as 6 The characters of
print(url[-6])
Running results :
i
y
Use [ ] In addition to getting a single character , You can also specify a range to get multiple characters , That is, a substring or fragment , The specific format is :
strname[start : end : step]
A description of the parts :
【 example 1】 Basic usage :
url = 'http://c.biancheng.net/java/'
# Get index from 7 Go to 22( It doesn't contain 22) The string of
print(url[7: 22]) # Output zy
# Get index from 7 Go to -6 The string of
print(url[7: -6]) # Output zyit.org is very
# Get index from -21 To 6 The string of
print(url[-21: -6])
# From the index 3 Start , every other 4 Characters take out a character , Until the index 22 until
print(url[3: 22: 4])
Running results :
c.biancheng.net
c.biancheng.net
c.biancheng.net
pcaen
【 example 2】 Advanced usage ,start、end、step All three parameters can be omitted :
url = 'http://c.biancheng.net/java/'
# Get from index 5 Start , Substring up to the end
print(url[7: ])
# Get from index -21 Start , Substring up to the end
print(url[-21: ])
# Intercept the string from the beginning , Until the index 22 until
print(url[: 22])
# every other 3 Characters take out a character
print(url[:: 3])
Running results :
c.biancheng.net/java/
c.biancheng.net/java/
http://c.biancheng.net
hp/bne.ta/