Hello, I’m Brother Nongfei, thank you for reading this article, welcome one key three.


This article focuses on the various common methods of using strings in Python. Strings are often used in real-world development, so it is important to be familiar with them.


Full of dry goods, suggested collection, welcome to one 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, do not have nannies, do not have strings, and do not have strings. Only used in dry] (https://feige.blog.csdn.net/a… , this article will provide a detailed introduction to the various common uses of strings. Welcome everyone’s opinion triplet oh.

String concatenation

Through the + operator existing string code Nongfei brother good, requires the string code Nongfei brother niubi splicing to its back, to generate a new string code Nongfei brother good, code Nongfei brother niubi for example:

Print (str6 =' str6 ') print(str6 =' str6 ') print(str6 =' str6 ') print(str6 =' str6 ')

The running result is:

+ operator concatenation = code Nongfei brother good, code Nongfei brother awesome

String truncation (string slicing)

Slice is another way to access a string. It accesses a range of elements. Slice generates a new string. The syntactic format of the slicing operation is:

sname[start : end : step]

The meaning of each parameter is:

  1. Sname: Represents the name of the string
  2. Start: Indicates the start index position of the slice (including the position). This parameter can also be unspecified. If not specified, it will default to 0, that is, slicing starts from the beginning of the sequence.
  3. END: Indicates the end index position of the slice (excluding this position). If not specified, it defaults to the length of the sequence.
  4. Step: represents the step size, that is, in the slicing process, the element is taken at every few storage locations (including the current location). That is to say, if the value of step is greater than 1, for example, when step is 3, the next element will be taken at every two locations during the slicing. Let me give you an example:
Print (str1[7]) print(str1[0:7]) print(str1[0:7]) print(str1[0:7]) print(str1[0:7]) Print (str1[-9:-2]) print(str1[-9:-2]) print(str1[-9:-2]) print(str1[-9:-2])

The result of the run is:

To good good study, good study every day, every day

Split string

Python provides the split() method for splitting strings. The split() method splits a string into substrings with a specified delimiter. These substrings are stored in a list (without the delimiter) and returned as the return value of the method. The basic syntax format of this method is as follows:

str.split(sep,maxsplit)

The meanings of the parameters of each part in this method are:

  1. STR: Represents the string to be split
  2. Sep: Used to specify a delimiter that can contain multiple characters. This parameter defaults to None, which means all null characters, including Spaces, newline “\n”, TAB “\t”, etc
  3. Maxsplit: Optional parameter to specify the number of splits. The maximum number of neutron strings in the last list is maxsplit+1. If not specified or -1, there is no limit to the number of splits. In the split method, you cannot specify the maxsplit parameter without specifying the sep parameter. For example:
STR = 'https://feige.blog.csdn.net/' print (' do not specify a number of segmentation, STR split ('. ')) print (' specified number of segmentation for 2 times, STR., split ('. ', 2))

The running result is:

Do not specify a partition number [' https://feige ', 'blog', 'CSDN', '.net/'] specified partition number is 2 times [' https://feige ', 'blog', 'csdn.net/]

Merge strings

Merging strings is the opposite of splitting; Python provides the join() method to join multiple strings contained in a list (or tuple) into a single string. The grammatical structure is:

newstr = str.join(iterable)

The parameters of each part of this method are:

  1. Newstr: Represents the new string generated after the merge
  2. STR: Used to specify the delimiter at merge time
  3. Iterable: The source string data from which the merge operation is performed. It can be provided in the form of lists, tuples, and so on. Again, an example:
List = [' print ', 'print ',' print '] print(' print ', 'print') To concatenate ', '. '. The join (list)) print (' joining together by - ', '-'. Join (list))

The running result is:

By.. To join the code Nongfei brother. Study hard. It's great. By - stitching the code, Nongfei - study hard - it's great

Count the number of occurrences of the string

The count() method retrieves the number of occurrences of the specified string in another string, returning 0 if the retrieved string does not exist, or the number of occurrences otherwise. The grammatical structure is:

str.count(sub[,start[,end]])

The meaning of the parameters of each part of this method is:

  1. STR: Represents the original string
  2. Sub: Represents the string to retrieve.
  3. Start: Specifies the starting position of the retrieval, that is, the position from which the detection starts. If not specified, the retrieval starts from scratch by default.
  4. End: Specifies the point at which the search will end. If not specified, the search will continue to the end.
STR = 'https://feige.blog.csdn.net/' print (' statistics. ', STR. Count ('.')) print(' count from the first position to the fifth from the last position. ', STR. Count ('.', 1, -5))

The running result is:

Statistics. The number of occurrences 3 is counted from position 1 to the sixth from the last position. Number of occurrences 2

Checks if a string contains a substring

Python provides the find method to retrieve whether a string contains a target string, if so, returning the index of the first occurrence of the string, or otherwise returning -1. The grammatical structure is:

str.find(sub[,start[,end]])

The meaning of each parameter of this method is:

  1. STR: Represents the original string
  2. Sub: Represents the target string to retrieve
  3. Start: Represents the starting position from which to start the retrieval. If not specified, the retrieval will start from scratch by default
  4. End: Indicates the end of the search. If not specified, the search will continue to the end by default. Python also provides the rfind() method, which differs most from find() in that rfind() starts the retrieval from the right side of the string. Again, an example:
STR = 'yards farmers flying elder brother' print (' retrieval contains string "flying elder brother", STR., find (' flying elder brother ')) print (" search whether contain the string 'hello,' ", STR., find (' hello '))

The running result is:

Retrieves if it contains the string "Fei Brother" 2 Retrieves if it contains the string 'Hello' -1

Python also provides the indext() method to detect if a string contains a substring. The method takes the same arguments as the find method, except that the index() method throws an exception when the specified string does not exist. There is no need to repeat it here.

String alignment method

The Python STR provides three methods that can be used for text alignment: ljust(), rjust(), and center()

  1. Ljust () is used to align text to the left by padding the specified characters to the right of the specified string. The syntax is:
S.ljust(width[, fillchar])

The meaning of each parameter in this method is:

  • S: Represents the string to be populated
  • Width: represents the total length of the string, including the length of S itself
  • Fillchar: An optional parameter to specify the character to be used to fill a string. Spaces are used by default.
  1. The rjust() method is used to right-align the text by padding the specified character to the left of the string.
  2. The center() method is used to center text, rather than align it left or right. Here’s an example:
Str1 = 'https://feige.blog.csdn.net/' str2 = 'https://www.baidu.com/' print (" through - left-aligned ", str1. Ljust (30, '-')) print (" through self-realization left-aligned ", str2 ljust (30, '-')) print (" through - right-aligned ", str1. Rjust (30, '-')) print (" through - right-aligned, "str2. Rjust (30, '-')) print (" center alignment was achieved by - ", str1. Center (30, '-')) print (" center alignment was achieved by - ", str2. Center (30, '-'))

The running result is:

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/----

Whether the retrieve string begins with the specified string (startsWith ())

The startsWith () method retrieves whether a string begins with the specified string, and returns True if it does; Otherwise returns False. The grammatical structure is:

str.startswith(sub[,start[,end]])

The meaning of each parameter of this method is:

  1. STR: Represents the original string
  2. Sub: substring to retrieve ‘
  3. Start: Specifies the index of the starting position at which the search begins. If not, the search starts from scratch by default
  4. End: Specifies the index of the end position of the search. If not specified, the search continues until the end by default. For example:
Str1 = 'https://feige.blog.csdn.net/' print (' is it begin with HTTPS, str1. Startswith (' HTTPS ')) print (' is begin with feige, str1.startswith('feige', 0, 20))

The running result is:

Whether it starts True with HTTPS or False with feige

Whether the retrieve string endswith the specified string (endsWith ())

The endsWith () method is used to retrieve whether a string endswith the specified string, returning True if it does, or False if it does. The grammatical structure is:

str.endswith(sub[,start[,end]])

The meaning of each parameter of this method is the same as that of the startsWith method, so I won’t go into details here.

String case conversion (3) functions and usage

Python provides three methods for string capitalization

  1. The title() method is used to convert the first letter of each word in the string to uppercase and all other letters to lowercase. When the conversion is complete, this method returns the resulting string. If there are no characters in the string that need to be converted, this method returns the string intact. The grammatical structure isstr.title()
  2. Lower () is used to convert all uppercase letters in a string to lowercase letters, and when the conversion is complete, the method returns the newly obtained substring. If the string is already lowercase, the method returns the original string. The grammatical structure isstr.lower()
  3. Upper () is used to convert all lowercase letters in a string to uppercase letters, returning a new string if the conversion is successful. Otherwise, the original string is returned. The grammatical structure is:str.upper().

    Here’s an example:
Print (' lower ', STR. Lower ()) print(' lower ', STR. Upper ()) print(' lower ', STR. Upper ()) print(' lower ', STR.

The running result is:

The initials are capital Feige. All lowercase Feige. All capital Feige

Three ways to remove whitespace (remove special characters) from a string

Python provides three ways to remove whitespace (remove special characters) from a string. In this case, special characters are the pointer (\t), carriage return (\r), newline (\n), and so on.

  1. Strip () : Removes Spaces or special characters before and after the string (left and right)
  2. Lstrip () : Removes Spaces or special characters before (left) the string
  3. Python’s STR is immutable, so these three methods simply return a deleted copy of the space before or after the string. They do not change the string itself. Here’s an example:
STR = "\n" print(" strip ", STR. Lstrip ()) print(" strip ", STR. Lstrip ()) print(" strip ", STR. Lstrip ()) print(" strip ", STR. Lstrip ()) print(" strip ", STR. str.rstrip())

The running result is:

Remove the space before and after (special string). Remove the left space (special string). Remove the right space (special string)

The encode() and decode() methods: string encoding conversion

The earliest string encoding was ASCLL, which encoded only 10 digits, 26 uppercase and lowercase English letters, and a few special characters. ASCII could represent a maximum of 256 characters, each of which required only one byte. In order to be compatible with the characters of various countries, GBK, GB2312,UTF-8 encoding and so on appeared successively. UTF-8 is the international common encoding format, which contains all the characters needed by all countries in the world. It stipulates that English characters occupy 1 byte, and Chinese characters occupy 3 bytes.

  1. The encode() method provides a method for the string type (STR) to convert STR to bytes, a process also known as “encoding.” The grammatical structure is:str.encode([encoding="utf-8"][,errors="strict"])
  2. Converts binary data of type bytes to type STR. This process is also known as decoding, and its syntactic structure is:bytes.decode([encoding="utf-8"][,errors="strict"])

    Here’s an example:
STR = 'encode' Bytes = STR. Encode () print(' code ', bytes) print(' decode ', bytes. Decode ())

The running result is:

Encoding B '\xe7\xa0\x81\xe5\x86\x9c\xe9\xa3\x9e\xe5\x93\xa5\xe5\x8a\xa0\xe6\ xxb2 \ xxb9 'decoding code Nong Feiger

The default encoding format is UTF-8. The encoding and decoding format should be the same, otherwise the decoding will fail.

Serialization and deserialization

In practice we often serialize a data object to a string and deserialize a string to a data object. The serialization module that comes with Python is the JSON module.

  1. The json.dumps() method turns Python objects into strings
  2. Json. Loads () decodes encoded JSON strings into Python objects as an example:
The import json dict = {' student id: 1001, 'name' : "zhang", 'score' : [{' language ': 90,' mathematics' : 100}]} STR = json.dumps(dict,ensure_ascii=False) print(' Serialize to a string ', STR, Type (STR)) dict2 = json.loads(STR) print(' deserialization to object ', dict2, type(dict2))

The running result is:

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 '

conclusion

This article describes in detail the various common uses of the string STR in Python. It is essential that we master the various uses of STR.

I am Brother Nongfei. Thank you again for reading this article.


The whole network of the same name [code farm fly elder brother]. Enjoy the joy of sharing every single step, every single mile


I am Brother Nongfei. Thank you again for reading this article.