Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Python string operation
Python string operation
String manipulation is a common operation in various computer languages. Let's briefly introduce string operations in python.

I. Exponential operation

A string is composed of some continuous characters, which supports index operation, and the index position starts from 0. For example, the following code will output the "p" character:

Second, intercept the substring.

A string can also generate a new substring with a given start and end index like a list. For example, the following code will output "Py":

Third, the connection operation

Adding multiple strings will generate a new string, such as the following code output "Love Python":

Fourth, case conversion.

Calling the upper and lower methods of string will generate new uppercase and lowercase strings respectively, such as the following code: "I love python" for the first time and "I love PYTHON" for the second time:

Five, before and after the suffix judgment

Call the startswith and endswith methods of the string to determine whether the string ends with a substring or a substring. For example, the following will print out "python startswith py" and "python endswith on" respectively:

6. Find and replace substrings

Call the find method to determine whether it contains substrings. For example, the following code will output "python contains th" and "python does not contain he":

You can replace a string by calling the replace method. For example, replacing "hello" in "hello world" with "world" will output the following code: "world world"

Seventh, separate the rope.

What should we do if we want to separate a sentence into words with spaces? Just call the split method. For example, the following code will convert "hello world" into ["hello ","world ","ni ","hao"]:

Eight, clear before and after the characters

If there are blank characters before and after the string, we need to delete them. You can call the string substitution method, but it is easier to call the strip method. For example, the following code will delete white space characters at both ends and output "hello python":

IX. Case reversal

What should we do if we need to convert lowercase in a string to uppercase and uppercase to lowercase? It's simple. Just call swapcase, because the following code will output "heLLO pYThON":

Ten, character classification judgment

There are many ways to judge whether a string belongs to a certain category, such as isdigit judging whether it is a number, isalpha judging whether it is a letter, isalnum judging whether it is an alphanumeric and so on. , as follows: