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

Case Analysis of Common methods of Python string

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "case analysis of common methods of Python string". In daily operation, I believe that many people have doubts in the case analysis of common methods of Python string. The editor has consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "case analysis of common methods of Python string". Next, please follow the editor to study!

What is the object?

For Python, the concept of object is more like the concept of identity, we can understand that every variable is actually an object.

Everything in Python is an object.

Each object has its own properties and methods

The characteristic of an object is its properties, and its function is its method or function. For example, strings have many built-in functions to help us deal with strings.

Python, everything is an object.

There is a saying in Python: the object of interpretation of everything.

In the field of programming, real-world entities are often referred to as objects, such as:

Bananas, apples, oranges

Men, women, children.

Airplanes, subways, special cars

A bungalow, building, cottage

An object refers to a concrete entity and is not used to refer to an abstract group (or the group in which an entity belongs).

Banana is a specific fruit, so it can be said that banana is an object.

It is a kind of fruit, but fruit is an abstract concept, which refers to a group of edible plant fruits that contain more water and sugar.

You can say that bananas, apples and oranges are fruits, but you can't say that fruits can only be bananas, apples and oranges.

So we can't say that fruit is an object.

Similarly, specific means of transportation such as airplanes and subways can be called objects, but it cannot be said that vehicles are an object.

The index of a string

Before we learn the common methods of strings, let's kiss the index of strings.

Index []

Get the characters at the specified position in the string by indexing []. The example is as follows:

> s = 'Python' > s [0]' P' > s [1]'y' > s [2]'t'> s [3]'h' > s [4]'0' > > s [5]'n'

In Python, a single character is also treated as a string, that is, the string contains only one character

On line 2, get the 0th character'P' of the string s

On line 4, get the first character'y' of the string s

On line 6, get the first character't'of the string s

On line 8, get the first character'h' of the string s

On line 10, get the first character'o' of the string s

On line 12, get the first character'n' of the string s

Index [:]

In Python, use the syntax string [start:end] to get the substrings of the string string in the range of [start, end).

Note that the range [start, end) contains start, not end. It can also be understood as the left-closed and right-open principle of the list.

Examples are as follows:

> s = 'Python' > s [1]' y' > s [2]'t'> s [3]'h' > s [0:5] 'Pytho'

On line 2, get the first character'm'of the string s

On line 4, get the second character'o' of the string s

On line 6, get the third character'o' of the string s

On line 8, the string 'mooc', from 1 to 4 in the string s is represented by s [1:4], noting that the range includes the 1st character of the string, not the 4th character.

Common methods of string find () function and index () function

The function of the find () function and the index () function: both return the position of the member (element) you are looking for

Usage of the find () function: str = string.finde (item) item: to query the matching elements, return an integer

Usage of the index () function: str = string.index (item) item: to query matching elements, return an integer or report an error

The position in the string is calculated from left to right, starting with the subscript [0].

The difference between the find () function and index () function:

If the find () function cannot find a c member (element), it returns-1

If the index () function cannot find a member (element), it will cause the program to report an error

Info = "Python is good code" print (info.find ("P")) print (info.find ("good")) print (info.find ("Java")) # > > info.find ("Java")) > 1info = "Python is good code" print (info.index ("P")) print (info.index ("good") print (info.index ("Java")) # Direct error report (grammatical error) 'ValueError: substring not found'# > > grammar > > 10startswith (function) and endswith () function

The function of the startswith () function: to determine whether the start bit of a string is a member (element), you can specify the statistical range, [start,end) left closed interval, right open interval.

Usage of the startswith () function: str = string.startswith (item) item: to query the matching element, return a Boolean value

The function of endswith () function: to determine whether the end of a string is a member (element), you can specify the statistical range, [start,end) left closed interval, right open interval.

Usage of the startswith () function: str = string.endswith (item) item: to query the matching element, return a Boolean value

Examples are as follows:

Info = 'Python is good'print (info.startswith (' Python')) print (info.startswith ('Java')) print (info.endswith (' good')) print (info.endswith ('bad')) # > > True# > False# > > True# > Falsestring_test = "this is string example" print (string_test.startswith (' this')) # whether the string begins print (string_test.startswith ('string') with this 8)) # whether the string starting from the ninth character begins with string print (string_test.startswith ('this', 2,4)) # whether the string from the second character to the fourth character ends with this # > True# > > True# > Falsecapitalize () function

The function of capitalize: capitalize the first letter of a string

Usage of capitalize: str = string.capitalize ()

Examples are as follows:

> str = 'string' > str.capitalize ()' String'

Notes for capitalize ():

Valid for initials only

Valid for letters only

If it is already uppercase, it is invalid

Small exercise of capitalize () function

Convert han meimei to a standard English name, and print to realize that the last name and first name are capitalized.

Name_1= "han" name_2= "meimei" print (name_1.capitalize () +''+ name_2.capitalize ()) # > > output result 'Han Meimei'casefold () function and lower () function

The function of casefold () function and lower () function: lowercase all characters of a string

The usage of casefold () function and lower () function: str = string.casefold (), str = string.lower ()

Examples are as follows:

> str_01 = 'Hello' > str_01.casefold ()' hello' > str_02 = 'World' > str_02.lower ()' world'

Notes for the casefold () function and lower () function:

Valid only for letters of a string

Invalid letters that are already lowercase

Chinese = "Hello, World" english = "Hello,World" test_str = "test@1.com$OK" print (chinese.casefold ()) print (chinese.lower ()) print (english.casefold ()) print (english.lower ()) print (test_str.casefold ()) print (test_str.lower ())

Since both the casefold () function and the lower () function can convert all characters of a string to lowercase, what's the difference?

In fact, there is a difference. The lower () function has existed for a long time to lowercase strings, while the casefold () function has been introduced since the Python3.3 version. The lower () function lowercase English characters, but has no effect on other non-English characters such as German, so it's time for the casefold () function to show its skill.

Small exercises for casefold () function and lower () function

Convert all of the following three CAPTCHAs to lowercase

Str_1 = "NAh8"

Str_2 = "Sn6H"

Str_3 = "HKFM"

Str_1 = "NAh8" str_2 = "Sn6H" str_3 = "HKFM" print (str_1.lower ()) print (str_2.casefold ()) print (str_3.lower ()) upper () function

The function of the upper () function: capitalize all strings

The usage of the upper () function: str = string.upper ()

Examples are as follows:

> str = 'string' > str.upper ()' STRING'

Considerations for capitalize:

Valid only for letters of a string

Invalid letters that are already uppercase

Str_test = 'Hello World'print (str_test.upper ()) # >' HELLO WORLD'swapcase () function

The function of the swapcase () function: case conversion of characters in a string

The usage of the swapcase () function: str = string.swapcase ()

Note for the swapcase () function: valid only for letters of a string

Info_one = 'Python is good'info_two =' pthon web is so esay'print (info_one.swapcase ()) print (info_two.swapcase ()) zfill () function

The function of the zfill () function: define the length of the string. If the length of the existing string is not satisfied, the missing part is automatically filled with 0.

Usage of the zfill () function: str = string.zfill (width) width: the desired length of the new string

Note for the zfill () function: it has nothing to do with the character of the string; if the defined string length is less than the current string length, it will not change.

Info = "Hello World" print (info.zfill (10)) print (info.zfill (15)) print (info.zfill (20)) count () function

The function of the count () function is to count the number of occurrences of a string, or to return the number of occurrences of a member (element) of the current string

Usage of the count () function: str = string.zfill (item) item: the element of the number / number of queries

Note for the count () function: if the member (element) of the query does not exist, it returns 0

Info = 'Please send this message to those people who mean something to you,to those who have touched your life in one way or another,to those who make you smile when you really need it,to those that make you see the brighter side of things when you are really down,to those who you want to let them know that you appreciate their friendship. And if you don't, don't worry,nothing bad will happen to you,you will just miss out on the opportunity to brighten someone's day with this message. '' this_count = info.count ('this') you_count = info.count (' you') love_count = info.count ('love') print (the number of times of "this" is:' + str (this_count) + 'times') # > the number of times of "this" is: 2 times print (the number of times of "you" is:'+ str (you_count) + 'times ") # > the number of times of" you "is 11 The number of times of secondary print ('"love") is:'+ str (love_count) + 'times') # > the number of times of "maybe" is: 0 times of strip () function

The function of the strip () function: remove the specified elements on both sides of the string. The default is a space.

Usage of the strip () function: str = string.strip (item). Pass a member (element) you want to remove in parentheses. You can leave it empty.

Extension of the strip () function:

The passed-in element is invalid if it is not at the beginning or end

Lstrip removes only the specified elements or spaces at the beginning of the string

Rstrip only removes the specified element or space at the end of the string

Examples are as follows:

Info = 'Jack is a good boy' new_info_01 = info.strip () print (new_info_01) # > Jack is a good boynew_info_02 = info.strip (info) print (new_info_02) print (len (new_info_02)) # > > in fact, the 'new_info_02' here has been emptied in the north # > 0' new_info_02' length is 0text = 'abcde'text_lstrip = text.lstrip (' a') print (text_lstrip) # > > bcdetext_rstrip = text.rstrip ('e') print (text_rstrip) # > abcdreplace () function

The function of the replace () function: replace the old (old string) in the string with new (new string), and you can specify the number. The default-1 means to replace all.

Usage of the replace () function: str = string.replace (old, new, max)

Old: the element to be replaced

New: replace the element of old

Max: optional, which means to replace several. By default, all matching old will be replaced.

Examples are as follows:

Info = "hello, Neo" print (info.replace ("Neo", "Jack")) print (info.replace ("", "*", 1)) # > > hello, Jack# > hello,*Neoinfo_test = "hello world!!" new_info_01 = info_test.replace ("h", "H") new_info_02 = new_info_01.replace ("w", "W") print (new_info_02.replace ('!') 'Python')) # > Hello World Pythonjoin () function

The function of the join () function is to concatenate the elements in the sequence with specified characters to generate a new string

Usage of the join () function: str = "" .join (lists)

Examples are as follows:

Lists = ["a", "b", "c"] tuples = ("1", "2", "3") print ("*" .join (lists)) # > a*b*cprint ("@" .join (tuples)) # > 1x 2join 3

Knowledge point

Join (lists) is a common way to convert lists and tuples into strings

Only string elements can be stored in the list. Other types of elements will report TypeError: sequence item 0: expected str instance, int found.

Tuples can also be passed in.

Split () function

The function of the split () function: divide the string into lists according to str, and separate num+1 substrings if the parameter num has a specified value

The usage of the split () function: str = string.split (), the delimiter can be specified in parentheses

Use spaces to split the string into multiple words and return a list, as shown in the following example:

Info = 'Hello World Python Is Good'print (info.split (")) # > [' Hello', 'World',' Python', 'Is',' Good'] print (info.split (", 1)) # > ['Hello',' World Python Is Good']

By default, you use spaces to split a string into multiple words, and you can specify a delimiter in the split () method, as shown in the following example:

Info = 'Hello World:Python Is_Good'print (info.split (":")) # > the collection of functions of type bool returned in the [' Hello World', 'Python Is_Good'] string

It is a collection because we have several functions that return the bool type, so let's see which functions return the bool type.

Isspace () function

The function of the isspace () function is to determine whether a string is a string made up of spaces

Usage of the isspace () function: isspace_bool_type = string.isspace (), no arguments to pass, and returns a bool type

Examples are as follows:

String =''print (string.isspace ()) # > > Truenew_string =' hello world'print (new_string.isspace ()) # > False although there is a space in 'hello world', but there are other characters besides spaces, so False is returned

Note: it should be noted here that a string composed of spaces is not equal to an empty string, because spaces also occupy a length.

Istitle () function

The function of the istitle () function: to determine whether a string is a title type (that is, multiple words with the first letter in uppercase)

Usage of the istitle () function: istitle_bool_type = string.istitle (), no arguments to pass, and returns a bool type

Examples are as follows:

Info_01 = 'Hello Jack'info_02 =' hello jack'print (info_01.istitle ()) # > > Trueprint (info_02.istitle ()) # > False

Note that this function is only valid in English

Isupper () function and islower () function

Features:

The isupper () function determines whether the characters in the string are all uppercase

The islower () function determines whether all characters in a string are lowercase.

Usage:

Isupper_bool_type = string.isupper (), no parameter to pass, returns a bool type

Islower_bool_type = islower (), no parameter to pass, returns a bool type

Examples are as follows:

Text_01 = 'GOOD BYE'print (text_01.isupper ()) # > > Trueprint (text_01.islower ()) # > > False so far, the study on "instance analysis of common methods of Python strings" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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