Introduction to Python _ shard and index of strings string methods

  • 2020-06-01 10:07:23
  • OfStack

This article mainly introduced the string shard and index, string method.

Sharding and indexing of strings:

Strings can be sliced and indexed using string[X]. Sharding, in short, is taking one part of a string and storing it somewhere else.

In the following example, string[0] represents the first character, string[-1] represents the last character, and space counts as one character. If you want to intercept a paragraph of a character, you can use string[X:X], in which the colon must be in the English state. If you intercept from the beginning or from the end, you can directly omit the beginning and the end.


string = 'I am a Product Manager'
print(string[0])
print(string[2])
print(string[-1])
print(string[-3])
print(string[0:9])
print(string[4:])
print(string[:9])

Operation results:


I
a
r
g
I am a Pr
 a Product Manager
I am a Pr

Now, let's try one new word:


string = 'father and mother, i love you'
new_word = (string[0] + string[7] + string[11] + string[-10] +string[-8] + string[-3])
print(new_word)

The characters separated from the slices form a new word: family. Operation results:


family

String method:

Python is an object-oriented programming language for objects that have a variety of functional properties, known in the jargon as "methods". Take a look at the following example. Keep the last four digits of the phone number and replace the rest with "*" :


phone_number = '13098763773'
hiding_phone_number = phone_number.replace(phone_number[:7],'*' * 7)
print(hiding_phone_number)

It USES the substitution method: object.replace (), which replaces the number of digits you want to hide with an asterisk. Operation results:


*******3773

Next, try find() for the first occurrence of a substring in a string.


search = '130'
num_a = '13098763773'
num_b = '13461309856'
num_c = '15098763453'
print(str(num_a.find(search)))
print(str(num_b.find(search)))
print(str(num_c.find(search)))

When it returns negative 1, it is not found.

Operation results:


0
4
-1

So that's the end of this first video, and we'll talk a little bit about functions in the next video on Python.


Related articles: