current position:Home>[Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods

[Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods

2022-01-30 17:52:30 Mainong Feige

Hello! , I'm Manon Feige , Thank you for reading this article , Welcome to three links with one button . This paper mainly introduces Python Sequences and strings in data types , There are eggs at the end of the article
Dry cargo is full. , Recommended collection , Always look new when you use it . If you have any questions and need , Please leave me a message ~ ~ ~.

Preface

Last article we introduced Python Several of the built-in data types belong to digital data types . This article begins with the introduction of sequence types . This paper will first introduce the basic concepts and general methods of sequence , Then I will introduce Python The concept and basic usage of string in .

Sequence

What is the sequence ?

Sequence (sequence) refer to A memory space that can hold multiple elements , These elements are arranged in a certain order . Each element has its own position ( Indexes ), Through these locations ( Indexes ) To find the specified element . If you think of the sequence as a hotel , Then each room in the hotel is equivalent to each element in the sequence , The number of rooms is equivalent to the index of elements , Can be numbered ( Indexes ) Find the specified room ( Elements ).

What sequence types are there ?

Understand the basic concept of sequence , So in Python What sequence types are there in the ? As shown in the figure below :  Insert picture description here It can be seen from the picture that Python The Communist Party of China has 7 Two sequence types , They are text sequence types (str); Binary sequence type bytes and bytearray; list (list); Tuples (tuple); Collection types (set and frozenset); Range type (range) And dictionary type (dict).

1. According to the elements that can be stored

According to the elements that can be stored, the sequence types can be divided into two categories : Namely : Container sequence and flat sequence Container sequence : A sequence of elements that can accommodate different data types ; Yes list;tuple;set;dict Take a chestnut :

list=['runoob',786,2.23,'john',70.2]
 Copy code 

there list The saved elements have multiple data types , Existing string , There are also decimals and integers . Flat sequence : That is, a sequence that can only hold elements of the same data type ; Yes bytes;str;bytearray, With str For example , The same str Only characters can be stored .

2. Divided according to whether it is variable or not

According to whether the sequence is variable , It can be divided into variable sequence and immutable sequence . Variable here means : After the sequence is created successfully , Can I modify it , For example, insert , Modification and so on , If you can, it's a variable sequence , If not, it is an immutable sequence . The variable sequence has a list ( list); Dictionaries (dict) etc. , The immutable sequence has Yuanzu (tuple), The following articles will introduce these data types in detail .

What are the methods and features of sequences ?

The index of the sequence

When introducing the concept of sequence , Speaking of the index of elements in the sequence , So what is a sequence index ? It's actually the subscript of the position . If the C If you know something about arrays in language , We know that the index subscripts of the array are from 0 A positive number that starts to increase in turn , That is, the index subscript of the first element is 0, The first n The index subscript of an element is n-1. The same is true for the index of a sequence , By default, the index is recorded from left to right , Index value from 0 Began to increase , That is, the index value of the first element is 0, The first n The index value of the elements is n-1. As shown in the figure below :  Insert picture description here Of course with C The difference between arrays in language is ,Python It also supports that the index value is negative , The index of this class is counted from right to left . let me put it another way , Is to count from the last element , From index value -1 Begin to decline , That is to say n The index value of the elements is -1, The first 1 The index value of the elements is -n, As shown in the figure below :  Insert picture description here

Sequence slice

Slicing is another way to access sequence elements , It can access a range of elements , By slicing , Can generate a new sequence . The syntax format of slicing operation is :

sname[start : end : step]
 Copy code 

The meaning of each parameter is :

  1. sname: Represents the name of the sequence
  2. start: Indicates the start index position of the slice ( Including the location ), This parameter can also be unspecified , If not specified, it will default to 0, That is, slice from the beginning of the sequence .
  3. end: Indicates the end index position of the slice ( Does not include the location ), If you don't specify , The default is the length of the sequence .
  4. step: Indicating step size , That is, during the slicing process , Several storage locations ( Include current location ) Take one element , in other words , If step The value is greater than 1, such as step by 3 when , When slicing elements , There will be 2 Go to the next location to take the next element .

Let's take chestnuts as an example :

str1=' study hard , Day day up '
#  Take out the index and mark it as 7 Value 
print(str1[7])
#  From the subscript 0 Start taking value , Until the subscript is 7( barring ) The index of the value 
print(str1[0:7])
#  From the subscript 1 Start taking value , Until the subscript is 4( barring ) The index of the value , because step be equal to 2, So it's going to be 1 The values of the two elements are 
print(str1[1:4:2])
#  Take out the last element 
print(str1[-1])
#  From the subscript -9 Start taking value , Until the subscript is -2( barring ) The index of the value 
print(str1[-9:-2])
 Copy code 

The result of the operation is :

 towards 
 study hard , Day after day 
 Good habits 
 On 
 study hard , Day after day 
 Copy code 

Sequence addition

Python Support the use of two sequences of the same type "+" Operator to do the desired addition operation , It will connect two sequences , But it doesn't remove duplicate elements , That is, just make a simple splicing .

str=' His name is Xiao Ming '
str1=' He is very clever '
print(str+str1)
 Copy code 

The result of the operation is : His name is Xiao Ming. He is very clever

Sequence multiplication

Python Support the use of numbers n Multiply by a sequence , It will generate a new sequence , The content of the new sequence is that the original sequence is repeated n Results of .

str2=' How are you? '
print(str2*3)
 Copy code 

The result of the operation is : Hello, Hello, hello , The contents of the original sequence are repeated 3 Time .

Check whether the element is included in the sequence

Python Can be used in in Keyword to check whether an element is a member of a sequence , Its grammatical form is :

value in sequence
 Copy code 

among ,value Indicates the element to check ,sequence Represents the specified sequence . Take a chestnut : lookup God Whether the word is in the string str1 in .

str1=' study hard , Day day up '
print(' God ' in str1)
 Copy code 

The result of the operation is :True

Sequence dependent built-in functions

function function Applicable scenario
len() Calculate the length of the sequence , That is, how many elements are included in the return sequence Applicable to list , Tuples 、 Dictionaries 、 aggregate 、 String, etc.
max() Find the largest element in the sequence , For the case where the elements in the sequence are numbers . Applicable to list , Tuples 、 Dictionaries 、 aggregate 、range etc.
min() Find the smallest element in the sequence , For the case where the elements in the sequence are numbers Applicable to list , Tuples 、 Dictionaries 、 aggregate 、range etc.
list() Convert sequence to list For Strings
str() Convert sequence to string Applicable to list , Tuples , Numbers
sum() Sum the elements in the sequence , Be careful , Use... For sequences sum() Function time , The sum operation must be all numbers , Cannot be a character or string , Because the interpreter can't decide what to do to connect , Add and operate Applicable to list , Tuples 、 aggregate 、range etc.
sorted() Sort the elements Applicable to list , Tuples 、 Dictionaries 、 aggregate 、range, String, etc.
reversed() Elements in reverse sequence Applicable to list , Tuples 、 Dictionaries 、 aggregate 、range, String, etc.
enumerate() Enumerate list elements , Return enumeration object , Each of these elements contains a tuple of subscripts and values . This function pairs tuples / Strings are also valid . Applicable to list , Tuples 、 Dictionaries 、 aggregate 、range, String, etc.
It's still an example :
str3=' Manon Feige '
print(' Length of string =',len(str3))
print(' Convert to list =',list(str3))
print(' call enumerate function ',enumerate(str3))
print(' Traverse enumerate The result of the function :')
for item in enumerate(str3):
    print(item)

print(' Traverse reversed The result of the function :')
for item in reversed(str3):
    print(item)

list2=[' Code the agriculture ',' Feige ']
print(' List to string =',str(list2))
list1=[12,20,5,8,1]
print(' Maximum =',max(list1))
print(' minimum value =',min(list1))
print(' Summation result =',sum(list1))
print(' Sorting result =',sorted(list1))
 Copy code 

The result of the operation is :

 Length of string = 4
 Convert to list = [' code ', ' farmers ', ' fly ', ' Brother ']
 call enumerate function  <enumerate object at 0x7f90818cd540>
 Traverse enumerate The result of the function :
(0, ' code ')
(1, ' farmers ')
(2, ' fly ')
(3, ' Brother ')
 Traverse reversed The result of the function :
 Brother 
 fly 
 farmers 
 code 
 List to string = [' Code the agriculture ', ' Feige ']
 Maximum = 20
 minimum value = 1
 Summation result = 46
 Sorting result = [1, 5, 8, 12, 20]
 Copy code 

character string

When I introduced the sequence earlier , Most examples are represented by strings , So let's get to know the string !

Definition of string

A set of several characters is a string (str),Python The string in must be in double quotes "" Or single quotes '' Surround . Its grammatical form is :

" String content "
' String content '
 Copy code 

If the string contains single quotation marks, special treatment is required . For example, now there is such a string str4='I'm a greate coder' It's wrong to write directly like this . There are two ways to deal with it :

  1. Escape Quotes , By escape symbol \ Escape :
str4='I\'m a greate coder'
 Copy code 
  1. Surround strings with different quotes
str4="I'm a greate coder"
 Copy code 

Use double quotation marks here , Single quotation marks in the package string .

Processing of the original string

Sometimes we don't want strings to be escaped , In this case, you can add... At the beginning of the string r Prefix , It becomes the original string , The specific format is :

str1 = r' Original string content '
str2 = r" Original string content "
 Copy code 

Let's give you an example :

str4=r' Code the agriculture \' Feige is great '
str5=r" Code the agriculture \' Feige is great "
print(str4)
print(str5)
 Copy code 

The result of the operation is :

 Code the agriculture \' Feige is great   Code the agriculture \' Feige is great   Copy code 

String segmentation method

In actual development , We often get the suffix of the file according to the file name , How to deal with this ?

path = "test_user_info.py"
 Copy code 

Now we're going to extract the suffix py, You can actually go through split Method , Split a string into lists (list), Then take a value from the list , It looks like this :

suffix = path.split(".")[1]
print("suffix: {}".format(suffix))
 Copy code 

String splicing method

There are three methods of string splicing , Namely :

  1. adopt join Method

adopt join The syntax format of the method is str.join(iterable), among join Is the condition of iterable Iterable , And the list element is a string (str). That's right iterable Each element in the , Then splice it to str On , there str Is used to specify the separator when merging , If you want the string after splicing to be comma separated , So the writing is 2. adopt format Method format The method is to occupy the position of the string to be spliced through placeholders . 3. adopt + Operator Existing string Hello, Manon Feige ,, Requires that the string be Manon, Feige, Niubi Stitched to the back , Generate a new string Hello, Manon Feige , Manon, Feige, Niubi

str6 = ' Hello, Manon Feige ,'
#  Use +  Operation symbol 
print('+ The result of operator splicing =',(str6 + ' Manon, Feige, Niubi '))
# Use join String concatenation 
list2 = [' code ', ' farmers ', ' fly ', ' Brother ', ' cattle ', ' forced ']
print(' Unsigned segmentation join The splicing results of =', ''.join(list2))
print(' Comma split join The splicing results of =',   ','.join(list2))
#  Use format Splicing 
str7 = str6 + '{0}'
print('format The result of the stitching =',str7.format(' Manon, Feige, Niubi '))
str8=str6+'{0}{1}'
print('format The result of the stitching =',str8.format(' Manon Feige ',' frigging awesome '))
 Copy code 

The result of the operation is ;

+ The result of operator splicing =  Hello, Manon Feige , Manon, Feige, Niubi 
 Unsigned segmentation join The splicing results of =  Manon, Feige, Niubi 
 Comma split join The splicing results of =  code , farmers , fly , Brother , cattle , forced 
format The result of the stitching =  Hello, Manon Feige , Manon, Feige, Niubi 
format The result of the stitching =  Hello, Manon Feige , Manon, Feige, Niubi 
 Copy code 

Let's think about it. If you still use it directly str6.join(' Manon, Feige, Niubi ') What is the final output ?

str6 = ' Hello, Manon Feige ,'
print(str6.join(' Manon, Feige, Niubi '))
print(str6)
 Copy code 

The result of the operation is

 Brother mainongfei is good , Brother Nong Ma Nong Fei is good , Feimainong Feige is good , Brother Ma Nong Fei is good , Brother Niu mannongfei is good , forced 
 Hello, Manon Feige ,
 Copy code 

Will be Manon, Feige, Niubi Traverse , Then each character is spliced into str6 front , So the preceding str6 As a concatenated separator . It should be noted that the spliced string is a new string , Instead of modifying the original string . So we see the original string str6 It doesn't change after splicing . This is very new and Java Medium String It's the same , So some friends know str An immutable cause ? Welcome to leave a message. . Therefore, when traversing the concatenated string, pay special attention to the assignment , Just like this. :

list = [' code ', ' farmers ', ' fly ', ' Brother ', ' cattle ', ' forced ']
str_list = str("")
for str1 in list:
    str_list = str_list + "file {0}\n".format(str1)
print(str_list)
 Copy code 

summary

This article introduces in detail Python Sequence type in built-in data type , The basic concept of sequence is introduced , A sequence is a memory space that stores multiple elements , These elements are arranged in a certain order , This paper introduces the generality of sequences , You can think of sequences as arrays in other languages , Think of the sequence as a hotel . The sequence uses an index to find the value inside . Finally, the string , I hope it can help readers .

Give it a try

The existing string is as follows

str6=' Programming apes are creating the world '
 Copy code 
  1. How to base on str6 The output is Zhengchuang String ?
  2. How to base on str6 The output is The silent ape sequence created by the world The string of ?

You are welcome to leave a message , Let's talk about . See the end of the article for the reference answers :

Refer to the answer

The existing string is as follows

str6=' Programming apes are creating the world '
 Copy code 
  1. How to base on str6 The output is Zhengchuang String ?
  2. How to base on str6 The output is The silent ape sequence created by the world The string of ?

Here we mainly investigate the slicing of strings and the splicing of strings . The inversion function is also used here .

  1. Answer 1 :
str6 = ' Programming apes are creating the world '
#  The coordinates of the index are from 0 At the beginning ,3 Take the first place 4 A string ,6 Represents to the seventh string ( barring ), Step length is 2
print(str6[3:6:2])
#  First get the inverted string 
str2 = ''.join(reversed(str6))
# Splice the string into the characters we want 
print(str2[0:4] + ' Silent ' +str2[6:9])
 Copy code 
  1. Answer two :
str6 = ' Programming apes are creating the world '
#  The first question is 
print(str6[3]+str6[5])
#  The second question is 
str6=str6[0:3]+str6[5:]
list2 = list(reversed(str6))
list2.insert(4, ' Silent ')
print(''.join(list2))
 Copy code 

I'm Manon Feige , Thank you again for reading this article . The whole network has the same name 【 Manon Feige 】. Short step , A thousand miles , Enjoy sharing I'm Manon Feige , Thank you again for reading this article .

copyright notice
author[Mainong Feige],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301752280711.html

Random recommended