Python string slicing and indexing
Python String Slicing and Indexing. Strings can be indexed and sliced using the string[x]
format, which adds a []
. String slicing can be thought of as finding the desired content from a string, copying a small segment of the desired length, and storing it elsewhere without modifying the original string. Each string obtained from the slice can be thought of as a copy of the original string.
First, let’s look at the following code. If you are confused and have no idea about the inexplicable numbers after the string variable, you may want to analyze it by referring to the table below the code.
name = 'My Name is Mike'
print(name[0])
'M'
print(name[-4])
'M'
print(name[11:14]) # from 11th to 14th, 14th one is excluded
'Mik'
print(name[11:15]) # from 11th to 15th, 15th one is excluded
'Mike'
print(name[5:])
'me is Mike'
print(name[:5])
'My Na'
:
represents the start and end of the string slice.
For example, name[11:14]
indicates the start and end of the string slice.
An expression like name[5:]
represents the string slice from character 5 to the end.
Conversely, name[:5]
represents the string slice from character 0 to character 5, but not including it. This can be confusing, but imagine the first one is from character 5 to the end, but the programmer is too lazy to count the number of characters, so they omit it. The second one is from the beginning to character 5, but again, because the programmer is too lazy to write the zero, they write it as [:5]
.
Okay, now let’s try solving a more complex problem and make a little word game called “Find the Evil in Your Friends”. Enter the code:
word = 'friends'
find_the_evil_in_your_friends = word[0] + word[2:4] + word[-3:-1]
print(find_the_evil_in_your_friends)
If it runs correctly, you’ll find the answer: fiend
, meaning you’ve found the evil in your friend. Got it?
Let’s take a look at an actual project application, again using sharding.
'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
'http://ww1.site.cn/85cc87jw1ex23yhwws5j20jg0szmzk.png'
'http://ww2.site.cn/185cc87jw1ex23ynr1naj20jg0t60wv.jpg'
'http://ww3.site.cn/185cc87jw1ex23yyvq29j20jg0t6gp4.gif'
Slicing is very useful in real-world projects. The URLs above (the URLs have been processed, so you can’t open them) are some of the image links parsed from the web pages after writing a crawler using Python. There are now more than 500 images with such links to download, which means I need to name these 500 images in different formats (png, jpg, gif) in a unified way. By observing the pattern, I decided to name the file using the last 10 characters from the link. So, I entered the following code:
url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
file_name = url[-10:]
print(file_name)
You will get the following result: 0kuwex.jpg