current position:Home>Fundamentals of Python I

Fundamentals of Python I

2022-01-29 10:57:47 Favor 316

This article has participated in 「 Digging force Star Program 」, Win a creative gift bag , Challenge creation incentive fund . Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities This article has participated in 「 Digging force Star Program 」, Win a creative gift bag , Challenge creation incentive fund . Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities

One character string

1.1 Definition of string

A string is actually a “ Orderly ” The character sequence of , Single quotation marks , Double quotes , A group of characters enclosed in three quotation marks , It's just a string , for example :

 Copy code 

1.2 Subscripts and slices

1.2.1 Subscript indices

The subscript is Python The concept in is the meaning of number , The concept of subscript is often used in string tuple lists , We can find their corresponding elements according to the subscript . For example, we created a string name = zhang , Now I want to get the name name In the string a character . How to get it ?, Can pass for Loop through the string , In this way, the characters in the string are extracted , however Python It provides us with a simpler method , We can use the subscript to take out a character


1.2.2 section

We can use the index in the following table to get the corresponding element in the string , But if you want to intercept an element, you need a slice . Slicing refers to the operation of intercepting part of the operation object . character string 、 list 、 Tuples all support slicing . The syntax of slicing : [ start : end : step ] Take string as an example to explain . If you take out a part , Can be in brackets [] in , Use :


1.2.3 String common operations

If there is a string mystr='hello world everyone', There are the following common operations 1,find testing str Whether to include in a string , If it is to return the index at the beginning , Otherwise return to -1


2, index Follow find () The method is the same , Just if str be not in mystr An exception will be reported in .

image.png 3, count return str stay start and end Between mystr The number of times it's inside

image.png 4, replace hold mystr Medium str1 Replace with str2, If count Appoint , The substitution does not exceed count Time .

image.png 5, split With str Slice for separator mystr, If maxsplit There is a specified value , Only separate maxsplit Substring

image.png 6, capitalize Capitalize the first character of a string

image.png 7, title

image.png 8, startswith Check if the string is set to str start , Yes, go back to True, Otherwise return to False

image.png 9, endswith Check whether the string uses obj end , If it's a return True , Otherwise return to False .

image.png 10, lower transformation mystr All uppercase characters are lowercase 11, upper transformation mystr The lowercase letter in is uppercase

image.png 12, rjust Returns an original string to the right , And fill it with Spaces to length width New string of 13, ljust Returns an original string left aligned , And fill it with Spaces to length width New string of 14, center Returns an original string centered , And fill it with Spaces to length width New string of 15, lstrip Delete mystr The white space on the left

image.png 16, rstrip Delete mystr White space at the end of a string 17 strip Delete mystr White space characters at both ends of a string 18, rfind Be similar to find() function , Just search from the right .

image.png 19, rindex Be similar to index(), It's just from the right .

image.png 20, partition hold mystr With str Divided into three parts , str front ,str and str after

image.png 21, rpartition Be similar to partition() function , It's just from the right .

image.png 22, splitlines Separate by lines , Returns a list of rows as elements

image.png 23, join mystr Insert after each element in the str , Construct a new string


Two list

2.1 List Introduction

Python One of the built-in data types is list :list.(list It's an orderly collection , You can add and remove elements at any time , Write between square brackets 、 A comma separated list of values . The items in the list don't have to be all of the same type . Than C The powerful thing about arrays in languages is that elements in lists can be of different types .

2.1.1 The length of the list


2.1.2 Access to the list

Visit with an index list Elements in every position in , The index is from 0 At the beginning :( From left to right ), Index from -1 Start ,( From right to left )


2.1.3 Slice of the list

Get part of the data according to the range of the subscript , such as : list , Strings can be sliced . Use format of slice data [ Start subscript : End subscript : step ] Tips : Start subscript default 0, The ending subscript does not contain , The default step size is 1


2.1.4 Additive elements (append,extend,insert)

1, append

image.png 2, extend

image.png 3,insert


2.1.5 Modifying elements

When modifying elements , The subscript is used to determine which element to modify , Then it can be modified


2.1.6 Look for the element

So called search , Is to see if the specified element exists .

2.1.7 Remove elements

The common ways to delete list elements are : del: Delete according to subscript pop: Delete the last element remove: Delete based on the value of the element




2.1.8 Sort

sort The method is to list Rearrange in a specific order , Default is from small to large , Parameters reverse=True It can be changed to reverse order , From big to small .



3、 ... and Tuples

Another kind of sequential table is called tuple : tuple .tuple and list Very similar , however tuple Once initialized, it cannot be modified , For example, it also lists the names of students :


  • Now? , classmates This tuple It can't be changed , It doesn't either append( ) , insert() This way . Other ways to get elements and list It's the same , You can use it normally classmates[0],classmates[-1], But it can't be assigned to another element .
  • Immutable tuple What's the point ? because tuple immutable , So the code is more secure . If possible , It works tuple Instead of list Try your best tuple.
  • If you want to define an empty tuple, It can be written. ():
  • Only 1 An element of tuple A comma must be added to the definition , To disambiguate ∶ Because the brackets ( It can express tuple, It can also represent the brackets in the mathematical formula .


Four Dictionaries

Dictionary is another variable container model , And can store any type of object . Let's have a class Each key value of the dictionary (key=value) Yes, with a colon (:) Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly braces

image.png Due to a key There's only one value , therefore , Many to one key Put in value, The value in the back will flush out the value in the front ; If key non-existent ,dict You're going to report a mistake

4.1 Dictionary common operation

4.1.1 Modifying elements


4.1.2 Additive elements

If you are using variable names [" key ]= Data time , This " key " In the dictionary , non-existent , So it's going to add this element . Add new elements image.png

4.1.3 Remove elements

Delete the dictionary , There are the following :

  • del
  • clear ( )

del Deletes the specified element


image.png clear Empty the whole dictionary


4.1.4 Measure the number of key value pairs in the dictionary


4.1.5 keys

Return a dictionary containing all key A list of


4.1.6 values

Return a dictionary containing all value A list of


4.1.7 items

Return one containing all ( key , value ) The list of Yuanzu


5、 ... and aggregate

aggregate (set) Is an unordered sequence of non-repeating elements . You can use braces or set() Function to create a collection , Be careful ∶ To create an empty collection, you must use the set() instead of {}, because {} Is used to create an empty dictionary .


image.png Collection can de duplicate container type data

image.png list , Tuples , The three sets can be converted to each other .

copyright notice
author[Favor 316],Please bring the original link to reprint, thank you.

Random recommended