Hello, I am Ma Nongfei ge, thank you for reading this article, welcome one button three lian oh. This article will focus on various common Python string methods. Strings are often used in practical development, so it is important to be familiar with their various uses. Dry goods full, suggest collection, welcome you to a key three even oh. If you have any questions or needs, please feel free to leave a message.
@[TOC]
preface
Python’s built-in data types — sequences and strings — do not have girlfriends, are not nannies, and are only useful to use. This article will provide a detailed introduction to the various common uses of strings. Everyone is welcome to comment on the triad.
String splicing
Use the + operator to concatenate the existing string code to the end of the string code, generating a new string code nongfeige good, code nongfeige niubi example:
str6 = 'Good for nongfei,'
# use the + operator
print('+ operator concatenation result =',(str6 + "Nongfeige Niubi"))
Copy the code
The results are as follows:
+ operator splicing result = code nongfei ge good, code Nongfei ge niubiCopy the code
String interception (string slice)
Slicing is another way to access a string. It can access a range of elements and, by slicing, generate a new string. The syntax format for a slice operation is:
sname[start : end : step]
Copy the code
The meanings of each parameter are as follows:
- Sname: indicates the name of the string
- Start: indicates the starting index position of the slice (including this position). This parameter can also be omitted. If this parameter is not specified, the default value is 0, that is, the slice starts from the beginning of the sequence.
- End: indicates the end index position of the slice (excluding this position). If not specified, the default value is the length of the sequence.
- Step: represents the step length, that is, in the process of slicing, the element is taken at several storage locations (including the current location) once. That is to say, if the value of step is greater than 1, for example, if step is 3, the next element will be taken at two locations during slicing.
Or an example to illustrate:
str1='Good good study, day day up'
Select * from index (7)
print(str1[7])
# select the value starting at index 0 and continuing until index 7 (not included)
print(str1[0:7])
# start at index 1 and continue until index 4 (not included). Step = 2, so one element is separated
print(str1[1:4:2])
Extract the last element
print(str1[-1])
# start at -9 and continue until the index is -2 (excluding)
print(str1[-9: -2])
Copy the code
The result of the run is:
Study well, study well every day, every dayCopy the code
Split string
Python provides the split() method to split strings. The split() method splits a string into substrings with specified separators. These substrings are stored in a list (without separators) and returned as the method’s return value. The basic syntax for this method is as follows:
str.split(sep,maxsplit)
Copy the code
The meanings of parameters in this method are as follows:
- STR: indicates the string to be split
- Sep: Specifies the separator. It can contain more than one character. This parameter defaults to None, indicating all empty characters, including Spaces, newline “\n”, TAB “\t”, and so on
- Maxsplit: This parameter is optional. It is used to specify the number of splits. The maximum number of substrings in the final list is maxsplit+1.
In the split method, if sep is not specified, then maxsplit cannot be specified either. For example:
str = 'https://feige.blog.csdn.net/'
print('Do not specify split times'.str.split('. '))
print('Specify split count as 2'.str.split('. '.2))
Copy the code
The results are as follows:
Do not specify a partition number [' https://feige ', 'blog', 'CSDN', '.net/'] specified partition number is 2 times [' https://feige ', 'blog', 'csdn.net/]Copy the code
Merge string
Merging strings is just the opposite of split. Python provides the join() method to join multiple strings contained in a list (or tuple) into a single string. Its grammatical structure is:
newstr = str.join(iterable)
Copy the code
The meanings of the parameters for each part of this method are:
- Newstr: indicates a new string generated after the merge
- STR: Used to specify the delimiter at merge time
- Iterable: Source string data for merging operations, which can be supplied as lists, tuples, etc.
Again, to illustrate:
list = ['Code Nongfei'.'Study hard'.'Very good']
print('Splice by.'.'. '.join(list))
print('Splice by -'.The '-'.join(list))
Copy the code
The results are as follows:
Splice code Nongfei with. Study hard. Very good pass. - Join the code Nongfego. - Study hard. - Very goodCopy the code
Count the number of occurrences of a string
The count() method retrieves the number of occurrences of a specified string in another string, returning 0 if the retrieved string does not exist, or the number of occurrences otherwise. Its grammatical structure is:
str.count(sub[,start[,end]])
Copy the code
The meanings of the parameters in each part of this method are:
- STR: indicates the original string
- Sub: Indicates the string to retrieve.
- Start: specifies the start location of the search. If this parameter is not specified, the search starts from the beginning.
- End: Specifies the end of the search. If not specified, the search continues to the end
Here’s an example:
str = 'https://feige.blog.csdn.net/'
print('Statistics. Number of occurrences'.str.count('. '))
print('from position 1 to position 5 from the bottom. Number of occurrences'.str.count('. '.1, -5))
Copy the code
The results are as follows:
Statistics. The number of occurrences of 3 from the first position to the last 6 position statistics. The number of occurrences 2Copy the code
Checks if a string contains a substring
Python provides the find method to find if the string contains the target string and returns the index of the first occurrence of the string if it does, or -1 if it does not. Its grammatical structure is:
str.find(sub[,start[,end]])
Copy the code
The meanings of the parameters of this method are:
- STR: indicates the original string
- Sub: Indicates the target string to be retrieved
- Start: indicates the start position for the search. If this parameter is not specified, the search starts from the beginning
- End: indicates the end of the search. If this parameter is not specified, the search continues to the end by default.
Python also provides the rfind() method, which differs from the find() method in that rfind() is retrieved from the right-hand side of the string. Again, to illustrate:
str = 'Code Nongfei'
print('Retrieves whether the string "Fly" is included..str.find('flying elder brother'))
print("Retrieve if it contains the string 'hello '".str.find('hello'))
Copy the code
The results are as follows:
Retrieves whether it contains the string "Fly brother" 2 Retrieves whether it contains the string 'hello' -1Copy the code
Python also provides an indext() method that checks if a string contains a substring. The method takes the same arguments as find, except that index() throws an exception when the specified string does not exist. I won’t repeat it here.
String alignment
Python STR provides three methods for text alignment: the ljust(), rjust(), and center() methods
- Ljust () is used to left-align text by padding the specified character to the right of the specified string:
S.ljust(width[, fillchar])
Copy the code
The meanings of the parameters in this method are:
- S: indicates the string to be filled
- Width: indicates the total length of the string including the length of S itself
- Fillchar: As an optional parameter, specify the characters to be used to fill the string. By default, Spaces are used.
- The rjust() method fills the left side of the string with specified characters to right-align the text.
- The center() method is used to center text, not left-aligned or right-aligned
Here’s an example:
str1 = 'https://feige.blog.csdn.net/'
str2 = 'https://www.baidu.com/'
print("Left alignment by -", str1.ljust(30.The '-'))
print("Left alignment by -", str2.ljust(30.The '-'))
print("Align right by -", str1.rjust(30.The '-'))
print("Align right by -", str2.rjust(30.The '-'))
print("Center alignment by -", str1.center(30.The '-'))
print("Center alignment by -", str2.center(30.The '-'))
Copy the code
The results are as follows:
Realize left-aligned through - https://feige.blog.csdn.net/ - by - through - right-aligned left-aligned https://www.baidu.com/-------- - https://feige.blog.csdn.net/ By - right-aligned -- -- -- -- -- -- -- -- https://www.baidu.com/ center alignment - through https://feige.blog.csdn.net/- - by - realizing centered alignment ----https://www.baidu.com/----Copy the code
Retrieves whether the string begins with the specified string (startswith())
The startswith() method is used to retrieve whether the string begins with the specified string, and returns True if so; Return False otherwise. Its grammatical structure is:
str.startswith(sub[,start[,end]])
Copy the code
The meanings of the parameters of this method are:
- STR: indicates the original string
- Sub: the substring to retrieve ‘
- Start: specifies the start index of the search. If this parameter is not specified, the search starts from scratch by default
- End: Specifies the index of the end location of the search. If not specified, the search continues to the end by default.
For example:
str1 = 'https://feige.blog.csdn.net/'
print('Does it start with HTTPS?', str1.startswith('https'))
print('Does it start with Feige?', str1.startswith('feige'.0.20))
Copy the code
The results are as follows:
Whether the value starts with HTTPS True Whether the value starts with feige FalseCopy the code
Retrieves whether the string endswith the specified string (endswith())
The endswith() method is used to retrieve whether the string ends in the specified string, returning True if so and False if not. Its grammatical structure is:
str.endswith(sub[,start[,end]])
Copy the code
The meaning of each parameter of this method is the same as that of the Startswith method, which I won’t go into here.
String case conversion (3 kinds) function and usage
Python provides three methods for string capitalization conversion
- The title() method is used to uppercase the first letter of each word in the string and lowercase all other letters. When the conversion is complete, this method returns the converted string. If there are no characters in the string that need to be converted, this method returns the string intact. Its grammatical structure is
str.title()
- Lower () is used to convert all uppercase letters in a string to lowercase letters, and when the conversion is complete, the method returns the new substring. If the string is already lowercase, this method returns the original string. Its grammatical structure is
str.lower()
- Upper () converts all lowercase letters in a string to uppercase letters, and returns a new string if the conversion succeeds; Otherwise, the original string is returned. Its grammatical structure is:
str.upper()
.
Here are some examples:
STR = 'feiGe 'print(' uppercase ', str.title()) print(' lowercase ', str.lower()) print(' uppercase ', str.upper())Copy the code
The results are as follows:
All caps Feige Brave Fly all caps Feige brave flyCopy the code
Three ways to remove whitespace (remove special characters) from a string
Python provides three ways to remove Spaces from strings (to remove special characters). Special characters here are table characters (\t), carriage returns (\r), newlines (\n), and so on.
- Strip () : Removes Spaces or special characters before and after the string
- Lstrip () : Removes Spaces or special characters before (left) the string
- Rstrip (): Removes Spaces or special characters following (right) the string
Python’s STR is immutable, so these three methods simply return a copy of the string after whitespace has been removed. They do not change the string itself, as an example:
str = 'n yard nongfei brother brave to fly'
print('Before and after whitespace (special string)'.str.strip())
print('Remove left whitespace (special string)'.str.lstrip())
print('Remove right space (special string)'.str.rstrip())
Copy the code
The results are as follows:
Remove the space before and after (special string) code Nongfei ge brave fly remove the left space (special string) code Nongfei ge brave fly remove the right space (special string) code Nongfei ge brave flyCopy the code
Encode () and decode() methods: string encoding conversions
The earliest string encoding is ASCll encoding, which only encodes 10 numbers, 26 upper and lower case English letters and some special characters. ASCII code can represent 256 characters at most, and each character takes only 1 byte. In order to be compatible with the characters of various countries, there have been THE EMERGENCE of GBK, GB2312,UTF-8 encoding, etc. Utf-8 is the international universal encoding format, it contains all the characters needed by all countries in the world, which requires that English characters occupy 1 byte, Chinese characters occupy 3 bytes.
- The encode() method provides a method for the string type (STR) to convert the STR type into bytes, a process also known as “encoding.” Its grammatical structure is:
str.encode([encoding="utf-8"][,errors="strict"])
- Converts bytes binary data to STR. This process, also known as “decoding”, is syntactic:
bytes.decode([encoding="utf-8"][,errors="strict"])
Here’s an example:
str = 'Come on, Nongfei.'
bytes = str.encode()
print('coding'.bytes)
print('the decoding'.bytes.decode())
Copy the code
The results are as follows:
Code b'\xe7\xa0\x81\xe5\x86\x9c\xe9\xa3\x9e\xe5\x93\xa5\xe5\x8a\xa0\xe6\ XB2 \ XB9Copy the code
The default encoding format is UTF-8. The encoding and decoding format must be the same; otherwise, the decoding will fail.
Serialization and deserialization
In practice, we often serialize a data object into a string and deserialize a string into a data object. Python’s built-in serialization module is the JSON module.
- The json.dumps() method converts Python objects into strings
- The json.loads() method decodes the encoded JSON string into a Python object
Here’s an example:
import json
dict = {'student id': 1001.'name': "Zhang".'score': [{'Chinese': 90.'mathematics': 100}}]str = json.dumps(dict,ensure_ascii=False)
print('Serialized to string'.str.type(str))
dict2 = json.loads(str)
print(Deserialize to object, dict2, type(dict2))
Copy the code
The results are as follows:
Serialized into string {" name ":" zhang ", "score" : [{" mathematics: "100," the language ": 90}]," student number ": 1001} < class 'STR' > deserialized into object {' name ':' Joe ', 'score' : [{' mathematics', 100, 'Chinese' : 90}], 'student number: 1001} < class >' dict 'Copy the code
conclusion
This article detailed the various common uses of the string STR in Python. It is our basic skill to master the various uses of STR.
I am Mynongfei and thank you again for reading this article. The whole network with the same name [code nongfei brother]. Thank you again for reading this article.