Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the general operation methods of Python string

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what are the conventional operation methods of Python string". In the daily operation, I believe that many people have doubts about the conventional operation methods of Python strings. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what are the conventional operation methods of Python strings?" Next, please follow the editor to study!

I. Preface

In the process of Python development, in order to achieve a certain function, it is often necessary to carry out special processing on some strings, such as splicing strings, intercepting strings, formatting strings and so on.

Second, concatenate strings

When the "+" operator can be used to concatenate multiple strings, the "+" operator can concatenate multiple strings and produce a string object.

For example, define two strings, one to save the English version and the other to save the Chinese version, and then use the "+" operator to concatenate the code as follows:

Mot_en = "Rememberance is a form meeting. Frgetfulness is a form of freedom" mot_cn = "memory is a meeting. Forgetting is a kind of freedom." Print (mot_en + "-" + mot_cn)

The running result of    is as follows:

Strings are not allowed to be concatenated with other types of data. For example, using the following code, concatenating a string with a numeric value will generate an exception.

Str1 = "Today's total walk" num = 23456str2 = "step" print (str1 + num + str2)

To solve this problem, you can convert the entire number to a string. You can use the str () function to convert a positive number to a string. The modified code is as follows:

Str1 = "Today's total walk" num = 23456str2 = "step" print (str1 + str (num) + str2)

Run the above code, and the result is as follows:

Third, calculate the length of the string

   because different strings occupy different bytes, so to calculate the length of a string, you need to know the number of bytes occupied by a string. In Python, numbers, English, decimal points, underscores and spaces take up one byte; a Chinese character can occupy 2 to 4 bytes, depending on the encoding used.

In Python, the len () function is provided to calculate the length of a string. The syntax format is as follows:

Len (str)

Where string is used to specify the string to be counted.

For example: define a string that reads "Life is too short, I use Python", and then use the len () function to calculate the length of the string. The code is as follows:

Str1 = "Life is too short, I use Python" # to define the string string = len (str1) # to calculate the string length print (string)

Executing the above code is displayed as "13"

In the actual development, it is sometimes necessary to obtain the number of bytes occupied by the string, that is, if UTF-8 coding is used, Chinese characters occupy 3 bytes, and when using GBK or GB2312, Chinese characters occupy two bytes, which can be encoded by encode () method and then obtained.

Str1 = "Life is too short. I use Python" # to define the string string = len (str1.encode ()) # to calculate the length of the UTF-8 encoded string print (string)

The result of running the code is as follows:

If you want to get the length of a string encoded in GBK, you can use the following code:

Str1 = "Life is too short. I use Python" # to define the string string = len (str1.encode ("gbk")) # to calculate the length of the GBK encoded string print (string)

The result of running the code is as follows:

IV. Intercept strings

Because the string also belongs to the sequence, you can use slicing to intercept the string. The syntax format for intercepting a string by slicing is as follows:

String [start: end: step]

Parameter description:

String: represents the string to be intercepted

Start: represents the index of the first character to be intercepted (including that character). If not specified, it defaults to "0"

End: indicates the index of the next character to be intercepted (excluding this character). If not specified, it defaults to the length of the string

Step: indicates the step size of the slice. If omitted, the default is "1". When the step size is omitted, the last colon can be omitted.

Define a character, and then intercept subcharacters of different lengths, as follows:

Str1 = "Life is short, I use the Python" # native string substr1 = str1 [1] # to intercept the second character substr2 = str1 [5:] # truncate substr3 = str1 [: 5] # truncate 5 characters substr4 = str1 [2:5] # truncate the 3rd to 5th characters print ("native string", str1) print (substr1 + "\ n" + substr2 + "\ n" + substr3 + "\ n" + substr4)

The running results are as follows:

During string interception, if the specified index does not exist, an exception is thrown, as shown in the following figure:

To solve this problem, you can use try... The except statement throws an exception with the following code:

Str1 = "Life is too short, I use Python" # Native string try: sbustr1 = str1 [15] except IndexError: print ("specified index does not exist")

The running results are as follows:

Fifth, separate strings

In Python, the string object provides a way to separate strings, which is to separate strings into lists.

The split () method of the string object can be split, and the syntax format of the split () method is as follows:

Str.split (sep,maxsplit)

Parameter description:

Str: represents the string to be split.

Sep: used to specify a separator, which can contain multiple characters. The default is None, that is, all empty characters (including spaces, newline "\ n", tab "\ t", etc.)

Maxsplit: optional parameter, which is used to specify the number of splits. If not specified or-1, there is no limit on the number of splits. Otherwise, the maximum number of elements that return the result list is maxsplit+1.

Return value: list of delimited strings

Note: in the split method, if the sep parameter is not specified, then the maxsplit parameter cannot be specified.

For example, define a string of Baidu URL, and then use the split () method to divide it according to different delimiters. The code is as follows:

Str1 = "Baidu address > https://www.baidu.com/" # print (" original string ", str1) list1 = str1.split () # split list2 = str1.split (" > > ") # with multiple delimiters list3 = str1.split (". ") # adopt". " Split list4 = str1.split (", 4) # use spaces to segment, and only split the first four print (str (list1) +"\ n "+ str (list2) +"\ n "+ str (list3) +"\ n "+ str (list4))

The running results are as follows:

VI. Retrieve string

In Python, string objects provide many methods that can be applied to string lookups. The following are mainly introduced here:

1.count () method

Retrieve the number of times the specified string appears in a string outside the column. The retrieval object does not exist, how to return 0, or the number of occurrences. The syntax is as follows:

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

Parameter description:

Str: represents the original string

Sub: represents the substring to retrieve

Start: optional parameter that represents the index of the starting position of the retrieval range. If not specified, it will be retrieved from scratch by default.

End: an optional parameter that represents the index at the end of the retrieval range. If not specified, the end is retrieved.

2.find () method

This method is used to retrieve whether it contains the specified substring, how to return-1 if the retrieval object does not exist, otherwise the index value that appears for the first time is returned. The syntax is as follows:

Str.findt (sub [, start [, end]])

Parameter description:

Str: represents the original string

Sub: represents the substring to retrieve

Start: optional parameter that represents the index of the starting position of the retrieval range. If not specified, it will be retrieved from scratch by default.

End: an optional parameter that represents the index at the end of the retrieval range. If not specified, the end is retrieved.

3.index () method

The index () method, similar to the find () method, is also used to retrieve whether the specified substring is included. However, using the index () method, an exception is thrown when the specified string does not exist, and the syntax format is as follows:

Str.index (sub [, start [, end]])

Parameter description:

Str: represents the original string

Sub: represents the substring to retrieve

Start: optional parameter that represents the index of the starting position of the retrieval range. If not specified, it will be retrieved from scratch by default.

End: an optional parameter that represents the index at the end of the retrieval range. If not specified, the end is retrieved.

4.startswith () method

This method is used to retrieve whether to specify the beginning of a string. If so, return True, otherwise return False. The syntax format is as follows:

Str.startswith (prefix [, start [, end]])

Parameter description:

Str: represents the original string

Prefix: represents the substring to retrieve

Start: optional parameter that represents the index of the starting position of the retrieval range. If not specified, it will be retrieved from scratch by default.

End: an optional parameter that represents the index at the end of the retrieval range. If not specified, the end is retrieved.

5.endswith () method

This method is used to retrieve whether to specify the end of a string. If so, return True, otherwise return False. The syntax format is as follows:

Str.endswith (prefix [, start [, end]])

Parameter description:

Str: represents the original string

Prefix: represents the substring to retrieve

Start: optional parameter that represents the index of the starting position of the retrieval range. If not specified, it will be retrieved from scratch by default.

End: an optional parameter that represents the index at the end of the retrieval range. If not specified, the end is retrieved.

Conversion of letters to lowercase and uppercase

In Python, the string object provides the lower () method and the upper () method for letter case conversion.

1.lower () method

Converts uppercase letters in a string to lowercase with the following syntax:

Str.lower ()

2.upper () method

Converts a string of lowercase letters to uppercase with the following syntax:

Str.upper () VIII. Remove spaces and special characters from the string

The special characters here refer to tabs "\ t", carriage returns "\ r", newline characters "\ n", and so on.

1.strip () method

The strip () method is used to remove spaces and special characters on the left and right sides of a string. The syntax is as follows:

Str.strip ([chars])

Parameter description:

Str: indicates that you want to remove the space string

Chars: optional parameter, which is used to specify the characters to be removed. Multiple characters can be specified. If chars is set to "@.", the "@" or "." included on the left and right sides will be removed. If not determined, the tabs "\ t", carriage returns "\ r", newline characters "\ n" and so on will be removed by default.

2.lstrip () method

The lstrip () method is used to remove spaces and special characters on the left, and the syntax format is as follows:

Str.lstrip ([chars])

Parameter description:

Str: indicates that you want to remove the space string

Chars: optional parameter, which is used to specify the characters to be removed. Multiple characters can be specified. If chars is set to "@.", the "@" or "." included on the left side will be removed. If not determined, the tabs "\ t", carriage returns "\ r", newline characters "\ n" and so on will be removed by default.

3.rstrip () method

The rstrip () method is used to remove spaces and special characters on the right. The syntax format is as follows:

Str.rstrip ([chars])

Parameter description:

Str: indicates that you want to remove the space string

Chars: optional parameter to specify the characters to be removed. Multiple characters can be specified. If chars is set to "@.", the "@" or "." included on the right side will be removed. If you do not know, the tabs "\ t", carriage returns "\ r", newline characters "\ n" and so on will be removed by default.

IX. Format string

There are two ways of string formatting in Python: the "%" operator and the format () method of the string object.

1. Use the "%" operator

[1]% formatting mode

% [(name)] [flags] [width]. [precision] typecode (name): optional, used to select the specified key flags: optional, optional values are: +: right alignment; positive numbers are preceded exactly, negative numbers are preceded by negative signs; -: left alignment; positive numbers are unsigned, negative numbers are preceded by minus signs; right alignment; positive numbers are preceded by spaces, negative numbers are preceded by negative signs 0: align to the right; positive numbers are unsigned, negative numbers are preceded by minus signs Fill in the blank width with 0: optional, occupy width. Width: optional, the number of digits retained after the decimal point typecode: required s, get the return value of the _ _ str__ method of the incoming object, format it to the specified position r, get the return value of the _ _ repr__ method of the incoming object, and format it to the specified location c Integer: converts a number to its unicode corresponding value, with a decimal range of 0

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report