Python string methods
Python string methods, Python is an object-oriented programming language, and objects have various functions and characteristics, which are professionally called methods. For ease of understanding, let’s assume that the car in our daily life is an “object”, that is, a car. As we all know, cars have many features and functions, one of which is “driving.” Therefore, the car object uses this function. In Python, we can express this as follows: car.drive()
Now that we understand object methods, let’s look at a scenario. Often, you use your phone number to register an account on a website. To ensure user information security, only the last four digits of the account information are displayed, with the rest replaced by *
. Let’s try using string methods to accomplish this.
Enter code:
phone_number = '1386-666-0006'
hiding_number = phone_number.replace(phone_number[:9],'*' * 9)
print(hiding_number)
Here, we use a new string method, replace(), for “masking.” In the replace method’s parentheses, the first phone_number[:9]
represents the portion to be replaced, and the following '*' * 9
indicates the character to be replaced. This means multiplying *
by 9, resulting in nine *
characters.
You’ll get the following result: *********0006
Now let’s try a more complex problem, simulating the phone number prediction feature in a mobile phone’s address book.
Note: This is just a rough guide to the solution; the actual implementation is much more complex.
Enter code:
search = '168'
num_a = '1386-168-0006'
num_b = '1681-222-0006'
print(search + ' is at ' + str(num_a.find(search) + 1) + ' to ' + str(num_a.find(search) + len(search)) + ' of num_a')
print(search + ' is at ' + str(num_b.find(search) + 1) + ' to ' + str(num_b.find(search) + len(search)) + ' of num_b')
You will get the following result, representing all mobile phone numbers containing 168
168 is between 6 and 8 of num_a
168 is between 1 and 3 of num_b