Why should we learn Python and its basic grammar

Eastmount 2020-11-13 00:01:09
learn python basic grammar

Welcome to “Python From zero to one ”, Here I'm going to share an appointment 200 piece Python Series articles , Take everyone to study and play together , have a look Python This interesting world . All articles will be combined with cases 、 Code and author's experience , I really want to share my nearly ten years programming experience with you , I hope it will be of some help to you , There are also some shortcomings in the article .

Python The overall framework of the series includes basic grammar 10 piece 、 Web crawler 30 piece 、 Visual analysis 10 piece 、 machine learning 20 piece 、 Big data analysis 20 piece 、 Image recognition 30 piece 、 Artificial intelligence 40 piece 、Python Security 20 piece 、 Other skills 10 piece . Your attention 、 Praise and forward is the greatest support for xiuzhang , Knowledge is priceless, man has love , I hope we can all be happy on the road of life 、 Grow up together .

This paper refers to the author and Mr. Xu CSDN The article , I really recommend you to study .

meanwhile , The author's new “ Na Zhang AI Safe house ” Will focus on Python And security technology , Mainly share Web penetration 、 System security 、 Artificial intelligence 、 Big data analysis 、 Image recognition 、 Malicious code detection 、CVE Reappear 、 Threat intelligence analysis, etc . Although the author is a technical white , But it will ensure that every article will be carefully written , I hope these basic articles will help you , stay Python And on the road to safety, progress with you .

One . First talk Python

Why study Python?
I'm learning Python Before , You don't have to worry about not having a foundation or “ Stupid brain ”, I always thought , As long as you want to learn and work hard for it , You can learn , Can use Python To do a lot of things . In this noisy era , A lot of technologies or concepts will continue to emerge , I hope you can settle down and study , Don't rush things , One step at a time . When you learn a technique well 、 After learning , There are still things that can be done , You can even find a job you like or finish a practical project .

Programming language is not the best , Only the best fit . As a beginner , I highly recommend that you study Python, Why? ? On the one hand, it has clear grammar 、 Code friendly 、 High readability , meanwhile Python With powerful third-party library functions , Including network crawling 、 Data analysis 、 visualization 、 Artificial intelligence, etc ; On the other hand Python It's an interpretive programming language , It's an object-oriented language again , Its operability and portability are high , It is widely used in data mining 、 information acquisition 、 Artificial intelligence 、 Network security 、 Automatic testing and other fields . even to the extent that , Many pupils 、 High school courses and computer level 2 have also been increased Python.

 Insert picture description here

Python advantage
Python The biggest advantage is efficiency . Sometimes the efficiency of programmers or researchers is more important than the efficiency of machines , For many complex functions , Using a clearer language can reduce the burden on the program , This greatly enhances the quality of the program , Its easy to learn and expansibility can also let the novice quickly start . although Python The bottom layer runs faster than C Slow language , but Python Clear structure frees programmers of their time , At the same time very convenient and other programming language code ( Such as C Language ) Merge together .

therefore , There has never been a programming language like Python It's rooted in so many fields at the same time , also Python Support cross platform operations , It also supports open source , Have a strong third-party library . Especially with the continued popularity of artificial intelligence ,Python stay IEEE The most popular languages released in recent years have ranked number one , More and more app enthusiasts 、 Technology followers are also learning Python.

 Insert picture description here

Python Study suggest
stay Python Learning process , Don't feel like you have a thin foundation or haven't touched before , Just want to give up , A lot of people don't choose to start or quit the race . I think , Just calm down , Willing to work hard , You can learn . In the learning process , Be sure to write code 、 Write code 、 Write code , I'm just starting to practice , Can accumulate slowly .

meanwhile , It's common to make mistakes in the process of writing code , I write now Python The code doesn't make mistakes every day , I was in a panic , So there was an error , Learn Baidu 、 It's really important for Google to solve this problem , It is also an improvement of your learning ability , There was no mistake , You can go to the open source forum 、 Community 、 Ask questions in Study Group , Welcome to the official account or CSDN Look for me .

Next, I'd like to give the recommendation of teacher Xu Python Programmer Growth Roadmap , Include : Basic grammar –> Language sense training –> Project practice –> Continue learning in different directions –> Intermediate programmer –> Expand depth and breadth –> Senior programmer .

 Insert picture description here

here , Give me learning Python Some of the process and skills of . I was the first to contact Python yes 2013 year , It's mainly because graduate students are majoring in natural language processing , Need to pass through Python Grab the data and analyze it , So I chose it . In those years Python There is very little information about , It's not that hot , But it has always been , Specific suggestions are as follows :

  • Install the environment first , Start writing the first one Python Code , Don't wait for tomorrow
  • Don't watch videos during learning ( Books ), Drinking milk tea , Is a day , You have to type the code
  • Usually first understand Python Basic grammar , recommend MOOC The video and runoob grammar , Of course B Station and CSDN There's also a lot of free information on , You can choose
  • After mastering the basic grammar, you can try to learn it Python Web crawler , Whether it's data analysis 、 machine learning 、 Penetration test, etc , It's going to involve crawler technology , Only if you have your own corpus , To deal with more problems . Don't go too far into reptiles , Master two techniques
    Urllib、Requests、BeautifulSoup、XPath、Selenium、Scrapy、 Distributed crawlers
  • Next learn Python Visual analysis ( The word cloud )、 Wechat operation 、 Email sending and other functions , This knowledge can effectively improve your interest in programming
  • The direction of AI : Including machine learning ( Return to | clustering | classification )、 Deep learning (TensorFlow | Keras | Pytorch) Study , It is suggested to conduct in-depth research in combination with actual scientific research or projects
  • Direction of image recognition : Including image processing 、OpenCV、 pattern recognition 、 machine learning 、 Deep learning 、 Target detection learning , It is also suggested to conduct in-depth research in combination with actual scientific research or projects
  • Learning in other directions :Web Website development 、 Network security 、 automated testing 、 Application programming

There is no shortcut to learning , Only insist on , But you can get through Python Constantly improve your interest in learning , Do something you like , Love the language . Finally, I give my junior year's study Python Words to motivate yourself :
If not now, when? If not me, who?
If it's not for yourself , For whom ; If it wasn't for fighting now , When will it start ?

Two .Python Introduction and installation introduction

1.Python brief introduction

Python Is the Dutch Guido van Rossum stay 1989 A new script interpretation language developed in , It is an object-oriented interpretive computer programming language .Python It's pure free software , Its grammar is concise and clear , One of the features is the mandatory use of white space (White Space) Indent as a statement . because Python Has a rich and powerful library , Often nicknamed glue language .

 Insert picture description here

Python As a hot language , It has the following characteristics :

  • Clear grammar , Code friendly , Easy to read
  • Widely applied , With a large number of third-party library support , Especially machine learning 、 Artificial intelligence related database
  • Python Strong portability , It is easy to operate various text files and databases to store data
  • Python Is an object-oriented language , Support the idea of open source
  • It can be used in a variety of functions 、 Script writing and rapid development on multiple platforms

The author and Mr. Xu have the same point of view , It is not recommended for beginners to choose something like Anaconda or PyCharm And other integration tools , In my opinion, the convenience they provide is not as much as the trouble for users to learn . At least , Don't use... In the first week IDE. about Python Such an interpretive scripting language , A handy editor is enough .

  • What we need is to focus on python In itself , Instead of being bothered by tool use problems . Have you noticed , Know more about Pycharm and Vscode Instructions for use 、 Solutions to common problems , More than discussion Python In itself
  • Many students are limited by the school computer , install Python The lightweight tools provided by the government are more convenient for learning
  • Run code manually , Can be more intuitive 、 Better understanding of script interpretation and execution process
  • Manual debugging code , Help code optimization , Improve code control ability
  • It can be used better pip Install and manage third party modules

Of course , These tools follow as you learn , The author will also popularize and share its functional usage .

  • Anaconda Python
  • PyCharm
  • Cpython
  • ActivePython
  • PyPy
  • Jython
  • Spyder

 Insert picture description here

2. The installation process

If you choose Windows Programming under the system , You can use the Python Official website Downloads Download the programming software from the page , Its official website is “http://www.python.org”. meanwhile , If you are in Linux Compiled under the system Python Code , You can use the Linux The system has built-in installation and use Python Interpreter .

 Insert picture description here

from Python When downloading from the official website , Please pay attention to choose the correct version . If it's for learning , There's no problem downloading the latest version , If it is used for production , Consider whether the third-party modules you need to develop support the latest version of Python. Be careful ,Python2 It has not been updated , I suggest that you learn Python3, They are basically similar in grammar , Only partial function modification . Here the author chooses to download Python3.6 or Python3.7.

 Insert picture description here

Don't forget to check the bottom two check boxes when installing , Otherwise, it will bring some trouble to the follow-up module installation , It is recommended to install by default .

 Insert picture description here

After successful installation , Need to be in “ Start ” Select... From the menu “ Program ”, Successfully installed Python Software , As shown in the figure , Open interpreter writing Python Code .

 Insert picture description here

open “Python 3.6(64-bit)” Command line software , Enter the first line Python Code “I love python”, The output result is shown in the figure below . The advantages of interpretive language , You can write a sentence and execute a sentence , Where to think and where to write , You don't have to write everything like a compiled language , It can only be run after the compilation is successful . I particularly like to use python Of IDLE, Even use it as a calculator .

 Insert picture description here

But if you need to write large pieces of code or custom functions ,Python The command line is certainly not a good choice , At this point, readers can click “IDLE”, function Python Integrated development environment (Python Integrated Development Environment,IDLE), You can use it to create or open .py Script files , Can edit 、 Operation and commissioning , Open as shown in the figure below .

 Insert picture description here

Then you can click “File” in “New File” New file , And save as py file , Such as “test01.py”, Then click Run “Run Module F5” Button , function Python Script files .

 Insert picture description here

all Python The file will be .py Extension name . Write the source code in test01.py Run... In file .

 Insert picture description here

A lot of times , We use it IDLE Verify that the code is written correctly , Check whether the module is successfully installed and the version number .IDLE Support tab Key auto complement , Often use this function to view the methods and properties of an object . Tips :

  • tab Key auto complement
  • Move the cursor over the executed statement and hit enter , You can repeat this command
  • Underline (_) You can get the last execution result

3、 ... and . Basic grammar

The front has been successfully installed Python Software , Let's start with Python Basic grammar of , Include indents and comments 、 Variables and constants 、 Input and output 、 Assignment, expression, etc .

1. Indent and comment

Different from other languages , stay Python The hierarchical relationship of code is indicated by indenting in .1 An indent is equal to 4 A space , It is Python The only way to indicate the framework of a program in a language .

stay Python in , Each statement in the same statement block is indented , And indent the same amount , When a statement block is rolled back or has been closed , You need to back off the indent of the previous level , Indicates the end of the current block . Here is C Language and Python Comparison of grammar , among C Language uses curly braces to distinguish hierarchical relationships ,Python Distinguish by indenting .

The number of indented blanks is variable , But all code block statements must contain the same amount of indented white space , This must be strictly enforced .

 Insert picture description here

Python quotes
Python You can use quotation marks ( ’ )、 Double quotes ( " )、 Three quotes ( ‘’’ or “”" ) To represent a string , The beginning and end of a quotation mark must be of the same type . Three quotation marks can be made up of multiple lines , Write fast syntax for multiline text , Commonly used for document strings , At the specific location of the document , As a comment .

word = 'eastmount'
sentence = " Na Zhang AI Safe house "
paragraph = """ This is a paragraph .
Contains multiple statements """

Comments are used to describe code information , Comment code is not executed .Python There are two main types of annotations :

  • Line notes : use # Start with a single line comment , Such as “# Define a variable ”.
# -*- coding: UTF-8 -*-
# file name :test01.py
# The first note 
print ("Hello World!") # The second note 
  • Block annotation : The comments of the multi line explanation use ’’' or """ The beginning and the end , For example, use Python Integrated development environment Spyder When creating a new file , There is usually a note .
Created on Sat Sep 16 10:34:31 2017
@author: yxz

Multi line statement
Python In a statement, a new line is usually used as the end of the statement . But we can use slashes ( \) Divide a line of statements into multiple lines to display , As shown below :

total = item_one + \
item_two + \

The statement contains [], {} or () Brackets do not need to use multiline connectors . The following example :

days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

2. Variables and constants

Variables are elements that can change values in a program , Is a named storage location in memory , The name of a variable that represents or refers to a value , For example, I hope to use N representative 3,name representative “hello” etc. . The naming rules are as follows :

  • Variable names are made up of uppercase and lowercase characters 、 Numbers and underscores (_) Combined .
  • The first character of the variable name must be a letter or an underline (_).
  • Python Variables in are case sensitive , such as “TEST” and “test” It's two variables .
  • stay Python When you assign a value to a variable in , Using single and double quotation marks has the same effect .
    Be careful ,Python Some of the keywords already used in cannot be used to declare variables , The key words are listed below :
['and', 'as', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

differ C/C++/Java Other languages ,Python Variables in do not need to be declared , You can directly use the assignment operator for its assignment operation , The data type is determined according to the assigned value , The figure below shows the type of undeclared output .

 Insert picture description here

A constant is an element that does not change the value of a program , A fixed value that cannot be modified once initialized , It's a unit in memory that holds fixed values . For some reason ,Python No information such as C/C++/Java Same const Modifier , In other words ,python There is no keyword that defines constants . however Python You can use object methods to create constants , Such as through const.py file , take const Class register to sys.modules Global dictionary

3. Input and output

Output usage print() Function implementation , Include output character information or variables , stay Python2 in , The output includes two formats :print a or print(a), Represents the output variable a Value . but Python3 Whitespace output is no longer supported , If you used Python2, We need to pay attention to these differences .

If you need to output multiple variables , Then use commas to connect , Such as print(a,b,c). A simple example is shown in the following figure ,print() Functions can output various types of variables .

  • print(a,b,c)
     Insert picture description here

meanwhile ,Python Support format output data , Need to call format() Function implementation , Its output format is :print(format(val,format_modifier)), The parameter val Indicated value 、format_modifier Format word , An example is shown in the figure below .

  • print(format(val,format_modifier))

 Insert picture description here

among “6.2f” Indicative output 6 Floating point number of digit value , To two places after the decimal point , The last bit of the output value is calculated by rounding , The final output is “12.35”.“.2%” Represents the percentage of output , Keep two significant digits , The output is “34.56%”. If you want to output an integer, use “.0f” that will do .

Python The input mainly includes input() and raw_input() Two functions .

  • input()
    input() Function to get the value entered by the user from the console , The format is :< Variable >=input(< Suggestive text >). The input result obtained is the string or value entered by the user , And save it in the variable . Examples of input strings and integers are as follows , among type() Function is used to find the type of a variable .
>>> str1 = input("input:")
input:"I am a teacher"
>>> print(str1)
I am a teacher
>>> age = input("input:")
>>> print(age,type(age))
25 <class 'str'>
  • raw_input()
    raw_input() Function is another input operation , And back to string character string . Input ends with a newline character , adopt help(raw_input) You can find help , The common format is :s = raw_input([prompt]), Parameters [prompt] Optional , Used to prompt the user for input . The sample code is as follows , First code input “hello world”, Second code input “25”.
>>> str1 = raw_input("input:")
input:hello world
>>> print(str1)
hello world
>>> age = raw_input("input:")
>>> print(age,type(age))
25 <type 'str'>

Be careful ,raw_input yes 2.x Version of the input function , Error will be reported in the new version environment , The function is undefined . stay 3.x It should be used in the version input() Instead of raw_input().

 Insert picture description here

4. Assignment and expression

Python The assignment statement in is using the equal sign (=) Assign values to variables directly , Such as “a=10”. If you need to assign values to multiple variables at the same time , The expression is as follows :

  • < Variable 1>,< Variable 2>,…,< Variable n> = < expression 1>,< expression 2>,…,< expression n>

It calculates the right side first N Expression , Then assign the result of the expression to the left variable at the same time . Examples are as follows :

>>> a,b,c = 10,20,(10+20)/2
>>> print(a,b,c)
10 20 15.0

An expression is a line of code in a program that generates or evaluates new data values , The assignment expression is as follows a=10, Usually by variables 、 Constants or operands produce expressions . To define an expression, pay attention to a few points :

  • A variable must be assigned a value before it can be used , Use assignment expressions to assign values to them .
  • Expressions also need to follow the indent rule at the beginning of a sentence , And you can't change the number of spaces .
  • You can add space in the expression , Make the program more readable , But spaces can't separate the way variables are named , such as “a = b + c”, Add space between operators .

Four . data type

End of story Python After basic knowledge , Let the author lead you to know Python Common data types .

1. Numeric type

Python Common numeric types include integer types 、 Floating point type 、 Plural type .

  • Integer types : The corresponding integer in Mathematics , Its return type is int type , Such as 10、25 etc. ;long It's long , It can also represent octal and hexadecimal .
  • Floating point type : Number with decimal point , The return type is float type , Such as 3.14、2.1e2 etc. .
  • Plural type :Python The complex number is divided into two parts , Form like a + bj, among a It is the real part ,b It is the imaginary part , The return type is complex, for example -12.3 + 8j. The plural can be passed through .real Get real data ,.imag Get virtual part data .
>>> z = -12.3 + 8j
>>> print(z, type(z))
(-12.3+8j) <type 'complex'>
>>> print(z.real, z.imag)
-12.3 8.0

Be careful :Python The number types in Chinese can be converted to each other , Where floating-point numbers are called int() Function to integer , Such as int(3.14) Return results 3, Integer call float() Convert to decimal , Floating point call complex() Function to complex number .

2. String type

The string type is Python Middle refers to a character or string that needs to be enclosed in single or double quotation marks . This type calls type(‘Python’) The result is str type . It is generally recorded as :

  • s=“a1a2···an”(n>=0)

A string represents a sequence of characters , Its leftmost end represents the starting position of the string , Subscript to be 0, Then increase in sequence . The number corresponding to a string is called “ Indexes ”, such as str1=‘Python’, be str1[0] Get the first character , namely “P” Letter , And strings provide some operations and functions for users to use , such as len(str1) Calculate string length , The return result is 6.

counter = 100 # Assign an integer variable 
miles = 1000.0 # floating-point 
name = "Eastmount" # character string 

python There are two order of values in the string list of :

  • Left to right index default 0 At the beginning , The maximum range is less string length 1
  • Right to left index default -1 At the beginning , The maximum range is at the beginning of the string

 Insert picture description here

If you want to get a substring from a string , have access to [ Header subscript : Tail subscript ] To intercept the corresponding string , The subscript is from 0 From the beginning , It can be positive or negative , The subscript can be empty to indicate that the head or tail is taken .[ Header subscript : Tail subscript ] The substring obtained contains the character of the header and subscript , But characters that don't contain trailing subscripts . such as :

>>> s = 'abcdef'
>>> s[1:5]

3. List the type

The list is Python A very important data type in , It's in brackets ([ ]) A collection of comma separated elements in , Can be accessed through a single element in the list , And every element is ordered . for example :

>>> list1 = [1, 2, 3, 4, 5]
>>> print(list1)
[1, 2, 3, 4, 5]
>>> print(list1[0])
>>> print(type(list1))
<type 'list'>
>>> list2 = ['I', 'am', 'a', 'teacher']
>>> print(list2)
['I', 'am', 'a', 'teacher']
>>> print(list2[3])

List can complete the data structure implementation of most collection classes . It supports characters 、 Numbers 、 Strings can even contain lists ( That is, nesting ). List with [ ] identification , yes Python The most common composite data type .

The cutting of the values in the list can also use variables [ Header subscript : Tail subscript ] , You can intercept the corresponding list , Left to right index default 0 Start , Right to left index default -1 Start , The subscript can be empty to indicate that the head or tail is taken .( Refer to the figure below runoob Website , I recommend you to study )

 Insert picture description here

Each element in the list can define a different data type , Such as list1 = [1, 1.3, ‘teacher’]. The operation method is similar to string , If the list uses the plus sign (+) Splicing 、 Use multiplier sign (*) Repeat display 、 You can also slice to get the child elements in the list , Examples are as follows :

>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [6, 7, 8]
>>> print(list1+list2)
[1, 2, 3, 4, 5, 6, 7, 8]
>>> print(list2*3)
[6, 7, 8, 6, 7, 8, 6, 7, 8]
>>> print(list1[2:4])
[3, 4]

The common methods in the list are shown in the following table , Hypothetical existence list list1 = [4, 2, 1, 5, 3].

 Insert picture description here

4. A tuple type

Tuple is a data type similar to a list , It uses parentheses to define a collection of one or more elements , Its return type is tuple. Examples are as follows :

>>> t1 = (12, 34, 'Python')
>>> print(t1)
(12, 34, 'Python')
>>> print(type(t1))
<type 'tuple'>
>>> print(t1[2])

Be careful : Empty tuples can be defined , Such as t2=(), Tuples can be accessed by index , Such as the above code t1[2] Access No. 3 Elements , namely “Python”. When a tuple is defined, it cannot be changed , You can't delete , This is different from a list , Due to the immutability of tuples , Its code is more secure .

The following is a tuple invalid , Because tuples are not allowed to be updated , The list is allowed to be updated . Error message :TypeError: ‘tuple’ object does not support item assignment, An error or... In a programming construct BUG It's very normal , Mo panic , Get rid of it .

# -*- coding: UTF-8 -*-
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Illegal application in tuple 
list[2] = 1000 # In the list are legitimate applications 

 Insert picture description here

5. Dictionary type

Dictionaries (dictionary) Except for the list python The most flexible type of built-in data structure . A list is an ordered collection of objects , A dictionary is an unordered collection of objects . The difference between the two is : The elements in the dictionary are accessed by keys , Instead of accessing by offset .

Dictionaries are provided for non sequential sets , Dictionary use "{ }" identification , By key value pair (< Key > < Value >) form , A dictionary is a collection of key value pairs , The type of dict. The key is the index of the dictionary , A key corresponds to a value , The key value can be used to find the information in the dictionary , This process is called mapping .

Examples are as follows , It can be obtained through key value pairs “4” Corresponding “Guiyang”.

>>> dic = {
>>> print(dic)
'1': 'Beijing', '3': 'Chengdu', '2': 'Shanghai', '4': 'Guiyang'}
>>> print(dic["4"])

There are several main differences between dictionaries and lists :

  • The elements in the list are ordered , The data in the dictionary is out of order .
  • They are mapped differently , Lists are mapped to values by address , Dictionaries are mapped to values through key value pairs .
  • The list can only be accessed by numeric subscript or index , Dictionaries can be accessed with various object types as keys .

Dictionary key values are very important for flexible applications , Especially web crawlers Json Format parsing , We will use it later in the actual case . Here is a simple code , The key is keys() and values() usage .

dict = {
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {
'name': 'runoob','code':6734, 'dept': 'sales'}
print(dict['one']) # The output key is one Value 
print(dict[2]) # The output key is 2 Value 
print(tinydict) # Output complete dictionary 
print(tinydict.keys()) # Output all keys 
print(tinydict.values()) # Output all values 

The output result is shown in the figure below :

 Insert picture description here

5、 ... and . String manipulation

I think string operation is also Python A very useful place , Whether it's data crawling 、 Big data analysis or text mining , Therefore, the author will take out this part separately to explain .

A string is an ordered set of character sequences , single quote 、 Double quotes 、 triple ( It can be done either alone or in pairs ) Quote , The string variable enclosed in triple quotation marks can be used to define the newline string . such as :

str1 = 'hello world'
str2 = "hello world"
str3 = """hello world"""

String supports formatted output , We need to introduce the operator percent sign (%) Realization , Place a formatted string to the left of the percent sign , Place the desired formatted value on the right side , But also tuples and dictionaries . for example :

>>> print("Hi!My Name is %s,I am %d years old and %f pounds heavy."%("YXZ", 26, 55.5))
Hi!My Name is YXZ,I am 26 years old and 55.500000 pounds heavy.

Output string in turn (%s)、 Integers (%d)、 Floating point numbers (%s) Three values . At the same time, strings support a variety of operations , Especially when dealing with text content , You need to use these methods and functions , Common functions are explained below .

Basic operation
The basic operations of a string include finding the length 、 Splicing 、 Repeat 、 Indexes 、 Slice and so on . hypothesis str1 String is “hello”,str2 String is “world”, be len(str1) Compute string str1 The length is 5;str1+str2 The result of splicing is “helloworld”;str1*3 The string is repeated and the result is “hellohellohello”.

String slicing is defined as s[i:j:step], among step Indicates the direction of the slice , Default start from 0 Start , Cut to the end without writing . for example :

str1 = 'abcdefghijklmn'
# def

The output is “def”, From 3 Values to get , The first 6 Value is the end point and does not get , namely str1[0]=‘a’,str1[3]=‘d’,str1[4]=‘e’,str1[5]=‘f’. Again , If you add step The parameter is negative , Represents slice from reverse . Positive direction first a The index subscript value is 0, the last one n The index subscript value is -1, The result is “nmlk”.

str1 = 'abcdefghijklmn'
# nmlk

find() function

  • usage : Find a substring from a string , The return value is the leftmost index of the location of the substring . Return if not found -1, Extended rfind() Method to find from right to left , It is often used in regular expression crawling data .
  • Example : Get string “def” The location of , Located at 3 A place ( from 0 Start counting ).
str1 = 'abcdefghijklmn'
num = str1.find('def')
print num
# 3

split() function

  • usage : String splitting function , Divide a string into sequences , Returns the split string sequence . If no separator is provided , The program will use all spaces as separators .
  • Example : By default, the string is split by space , You can also set the “+” Split string , The method splits the string 、IP extract 、URL Common suffix extraction .

 Insert picture description here

strip() function

  • usage : This function is used to remove the beginning and end space characters ( Does not contain spaces inside the string ), meanwhile S.strip([chars]) The specified character can be removed . Extended functions lstrip() Remove string start ( Leftmost ) All spaces for ,rstrip() Remove the end of a string ( Far right ) All spaces for .
  • Example : Remove the space between the front and back ends of the string .
>>> str1 = " I am a teacher "
>>> print(str1.strip())
I am a teacher

join() function

  • usage : String elements in a sequence are concatenated by a character , The element in the queue must be a string , Returns a concatenated string function , It can be said that join() The function is split() Inverse method of function .
  • Example : Using spaces (’ ') String concatenation [‘I’,‘am’,‘a’,‘teacher’], The code and output are as follows .
>>> num = ['I','am','a','teacher']
>>> sep = ' '
>>> str1 = sep.join(num)
>>> print str1
I am a teacher

6、 ... and . summary

in any case , The author hopes that this article can popularize some Python knowledge , I hope you can write code with me , Progress together . If the article can give you some trivial ideas and help with your research or project , It's even more gratifying . The author's biggest expectation is some stories in the article 、 word 、 Code or cases can help you , To those who struggle .

Words , The author passed the Python In fact, you can find some good jobs , But because I like teaching , Give up the Internet in Beijing , Choose to return to Guizhou , Become a college teacher . ha-ha , At that time, I wanted to go back to teach Python And big data knowledge , Although it's just a common choice , But I really hope I can stand in front of the podium , Keep your original mind , Teach more students 、 Popularize more Python Programming knowledge , Cultivate more data analysis for hometown 、 data mining 、 big data 、 Network security and other fields of talent , Make a modest contribution . Finally, the author left Beijing and chose to go back to Guizhou to teach :

Guizhou is a long way from zongmei ,
It's a bad time .
Three or four broken books were collected ,
I will teach you .

 Insert picture description here

Last , Thank you for your attention “ Na Zhang's home ” official account , thank CSDN So many years of company , Will always insist on sharing , I hope your article can accompany me to grow up , I also hope to keep moving forward on the road of technology . If the article is helpful to you 、 Have an insight , It's the best reward for me , Let's see and cherish !2020 year 8 month 18 The official account established by Japan , Thank you again for your attention , Please help to promote it “ Na Zhang's home ”, ha-ha ~ Newly arrived , Please give me more advice .

regret , Let's understand perfection .
Pass away , Let's move on .
Her posture in the night is so beautiful .

(By: Na Zhang's home Eastmount 2020-08-22 Night in Wuhan https://blog.csdn.net/Eastmount)

The references are as follows :
[1] Author books 《Python Network data crawling and analysis from the beginning to proficient 》
[2] The author blog :https://blog.csdn.net/Eastmount
[3] Xu teacher blog :https://blog.csdn.net/xufive/article/details/102993570
[4] https://www.runoob.com/python


  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database