The third day of learning python (pure beginner version)

Posted by faizanno1 on Wed, 08 Dec 2021 12:22:23 +0100

Article catalog

  • preface
  • 1, split() split and join() merge
  • 2, Small knowledge points
    • 1. String resident mechanism and string comparison
    • 2. Common search methods
    • 3. String formatting
    • 4. Variable string
    • 5. Basic operators
    • 6. Sequence (very important): string, list, tuple, dictionary, set
    • 7. Addition and deletion of list elements
    • 8. Deletion of list elements
    • 9. List element access and counting
  • summary




preface

I hope you can encourage each other!!! Just made a blog, I hope you can put forward valuable opinions on my blog, and I can correct it in time.




1, split() split and join() merge

Spit () can separate a string into multiple substrings (stored in a list) based on a delimiter. If no delimiter is specified, white space characters (newline / space / tab) are used by default

Example code:

a = "Act enthusiastic and you will be enthusiastic"
a.split()
a.split('be')
print(a.split('be'))

join() is the opposite of split(), which is used to connect a series of strings.

Example code:

a =['abc','abc123','abc2021']
'*'.join(a)
print('*'.join(a))
''.join(a)
print(''.join(a))

Key points of splicing string:

Using the string splicer + will generate a new string object, so it is not recommended to use + to splice strings. It is recommended to use the join function, because the join function will calculate the length of all strings before splicing strings, then copy them one by one, and create objects only once.

Example code: (test the efficiency of splicer + and join())

import time
time01 = time.time()  #Start time
a = ""
for i in range(1000000):
    a +="txt"
time02 = time.time()  #Termination time
print("Operation time:"+str(time02-time01))

time03 = time.time()  #Start time
li = []
for i in range(1000000):
    li.append("txt")
a="".join(li)
time04 = time.time()   #Termination time
print("Operation time:"+str(time04-time03))

2, Small knowledge points

1. String resident mechanism and string comparison

String resident: a method to save only one copy of the same and immutable string, and different values are stored in the string resident pool.
python supports string persistence mechanism. String persistence mechanism will be started for strings conforming to identification rules (only including underscores (), letters and numbers)




Example code:

a = "abc_123"
b = "abc_123"
print(a is b) #True
c = "da#"
d = "da#"
print(c is d) #False

Member operator:

Example code:

a = "abcdefgh"
print("a" in a) #True
print("bcd"in a) #Flase
print("aaa" in a) #Flase

2. Common search methods

a='''I'm Xiao Ming, 20 years old. I'm a college student. I'm studying hard python,I believe my efforts will be rewarded'''
len(a)  #String length
a.startswith('I'm Xiao Ming') #Starts with the specified string
a.endswith("Reciprocated")   #Ends with the specified string
a.find('learn')          #The first occurrence of the specified string
a.rfind('learn')         #The last occurrence of the specified string
a.count("learn")         #The specified string appears several times
a.isalnum()          #All characters are letters or numbers

Remove first information

Remove the specified information at the beginning of the string through strip(). lstrip() is used to remove the specified information on the left side of the string, and rstrip() is used to remove the specified information on the right side of the string.
strip() removes leading and trailing spaces

toggle case

a ="xiaoming love programming"
a.capitalize() #Generates a new string, capitalized
a.title()       #Generates a new string with each word capitalized
a.upper()       #A new string is generated, and all characters are converted to uppercase
a.lower()       #Generate a new string, and all strings are converted to lowercase
a.swapcase()        #Generate a new string and convert all letters to uppercase and lowercase

Format layout

The three functions center(), ljust(), and rjust() are useful for typesetting strings)

Example code:

a="ming"
a.center(10,"#")   #Center alignment
a.center(10)
a.ljust(10,"#")     #Align left
#Other methods
 #1. Is isalnum () # a letter or a number
 #2.isalpha() # check whether the string is only composed of letters (including Chinese characters)
#3.isdigit() # detects whether the string is only composed of numbers
 #4.isspace() # detects whether it is a null character
 #5.isupper() # is a capital letter
 #6. Is islower() # a lowercase letter

3. String formatting

Basic usage of format(): '{}'. Format()
Number format: floating point numbers are formatted through f and integers through d

Case:

a ="I am{0},What's my deposit{1:.2f}"
a.format("Xiao Ming",4000000.2325)
print(a.format("Xiao Ming",4000000.2325))

4. Variable string

In python, strings are immutable objects and cannot be modified in place. If you need to modify the values, you can only create new string objects.

However, sometimes we do need to modify the string in place. You can use io.StringIO object or array module.

import io
s = "hell,sxt"
sio = io.StringIO(s)
print(sio)
sio.getvalue()
sio.seek(8)
print(sio.seek(8))
sio.write("g")
print(sio.write("g"))

5. Basic operators

Priority of operators (multiplication and division, plus and minus, bitwise and arithmetic operations > comparison operators > assignment operators > logical operators

(5+10*x)/5-13*(y-1)*(a+b)/x+9*(5/x+(12+x)/y)

6. Sequence (very important): string, list, tuple, dictionary, set

Sequence: a data storage method used to store a series of data.
In memory, a sequence is a continuous memory space used to store multiple values, such as an integer sequence [10,20,30,40]

List: used to store any number and any type of data sets
#List creation:
a = [10,20,'xiaoming','xuexi']
a = []      #Create an empty list object
#list() creation: (use lsit() to convert any iteratable data into a list)
a = list()      #Create an empty list object
a = list(range(10))
print(a)
#range() creates a list of integers: range([start],end,[step])
#The start parameter is optional; the end parameter is required: it indicates the ending number; the step parameter is optional: it indicates the step size, which is 1 by default
a = [x*2 for x in range(5)]
print(a)

7. Addition and deletion of list elements

#When the list adds and deletes elements, the list will automatically carry out memory management, which greatly reduces the burden of programmers. However, this feature involves a large number of movement of list elements, which is inefficient.
#append() method: modify the list object in place. It is the fastest way to add new elements at the end of the real list. It is recommended.
a = [20,40]
a.append(80)
print(a)
#+Operator operation (completely generate new objects)
#extend() method: add all elements of the target list to the end of the list. This is an in place operation and does not create a new list object

a = [20,40]
print(id(a))
a.extend([80,160])
print(a)
print(id(a))
insert() insert element: use the insert() method to insert the specified element into any specified position of the list object. This will move all elements behind the insertion position and affect the processing speed.

Similar functions that perform this movement include remove(), pop(), del(). When deleting non tail elements, they will also move the elements behind the operation position
a = [10,20,30]
a.insert(2,100)     #Insert 100 at the position of 2, starting from 0, 1, 2
print(a)
Multiplication extension: use multiplication to expand the list to generate a new list. When a new list element, the original list element repeats many times.
a = ['abd',100]
b = a*3
print(a)
print(b)
#String and tuple are also suitable for multiplication

8. Deletion of list elements

#del delete: deletes the specified location in the list
A = [100,200,300,400,500,888]
del A[2]        #Delete the location of 300300 as 2
print(A)
pop() method: delete and return the element of the specified location. If no location is specified, the last element of the default action list.
a = [10,20,30,40,50,60]
a.pop()     #Delete end element
print(a)
c = a.pop(2) #Delete 30, and the position of 30 is 2
print(c)
remove() method: delete the specified element that appears for the first time, and throw an exception if it does not exist
a =[10,20,30,40,50,20,30]
a.remove(20)
print(a)
a.remove(888)       #Valueerror: list. Remove (x): X not in list

9. List element access and counting

Direct access to elements by index
ndex() gets the index of the first occurrence of the specified element in the list: you can get the index position of the first occurrence of the specified element.
Format: index(value,[start,[end]])
a = [10,20,30,40,888,20,30]
a.index(20)
a.index(20,3)       #The first 20 to search from index position 3
print(a.index(20,3))
count() gets the number of times the specified element appears in the list
len() returns the length of the list: that is, the number of elements contained in the list




Conclusion: it is inevitable to relax in learning. I am the same. Writing these is not only an encouragement to myself, but also an affirmation to myself. Come on

Topics: Python Machine Learning Data Mining