A string is composed of multiple characters, and there is an order between the characters. This sequence number is called the index. Python allows you to manipulate single or multiple characters in a string by indexing, such as getting the character at the specified index, and returning the index value of the specified character.
After you know the string name, you can access the corresponding character by using the index in square brackets []. The specific syntax is:
strname[index]
strname represents the string name, and index represents the index value.
Python allows indexing from both ends of a string:
For example:
a = "www.freelearningpoints.com" print(a[8]) #Get characters with index 8 print(a[-6]) #Get character with index sixth to the last character
The output is:
l
t
In addition to using [] to get a single character, you can also specify a range to get multiple characters, that is, a substring or fragment, the specific format is:
string_id[start : end : step]
Explanation of each part:
[Example 1] Basic usage:
a = "www.freelearningpoints.com" #Get index from 3 at 22 (not including 22) substring print (a [7: 22]) #Get substring with index from 7 to -6 print (a [7: -6]) #Starting at index 3, take one character every 4 characters until index 22 print (url [3: 22: 4])
The output is:
elearningpoints
telearningpoin
.ergn
[Example 2] Advanced usage, start, end, step three parameters can be omitted:
a = "www.freelearningpoints.com" #Get the substring from index 6 to the end print (a [6:]) #Get the substring starting at index-13 and ending at the end print (a [-13:]) #Truncate the string from the beginning until index 18 print (a [: 18]) #Take one character every 5 characters print (a [:: 5])
The output is:
eelearningpoints.com
ingpoints.com
www.freelearningpoints.co
wragtm
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises