程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes 2 standard data types

編輯:Python

First , We know Python 3 in , Yes 6 Standard data types , They are divided into variable and immutable .

Immutable data (3 individual ):

  • Number( Numbers )
  • String( character string )
  • Tuple( Tuples )

Variable data (3 individual ):

  • List( list )
  • Dictionary( Dictionaries )
  • Set( aggregate )

This is a Python 3 Medium 6 Standard data types , It includes their basic usage and common methods , It will be listed below , For future reference . First , We need to know about operators , Because these data types often use these operations and so on .


One 、 Operator


See :Python Operator


Two 、 Standard data type


1. Number( Numbers )

  • Python The number types of are int integer 、long Long integer 、float Floating point numbers 、complex The plural 、 And Boolean (0 and 1).
  • Python The number types of are int integer 、long Long integer 、float Floating point numbers 、complex The plural 、 And Boolean (0 and 1).

2. String( character string )

  • The string is Python The most commonly used data type in , We can use single quotes (’’) perhaps Double quotes ("") Create string .
  • Strings are made up of numbers 、 Letter 、 A string of underscores 、 Is the type of data that represents text in a programming language .

2.1 Processing strings

# String form : Use '' perhaps "" Create string 
str1 ='this is str1'
print(str1)

2.2 String commonly used methods

  • 2.2.1 toggle case
     # 1.upper() Converts all lowercase letters in a string to uppercase 
    # character string .upper()
    s1 = "hello Python"
    print(s1.upper()) # HELLO PYTHON
    #2.lower() Converts all uppercase letters in a string to lowercase 
    # character string .lower()
    s2 = "HELLO PYTHON"
    print(s2.lower()) # hello python
    #3.swapcase() Swap the upper and lower case letters in the string 
    # character string .swapcase()
    s3 = "hello PYTHON"
    print(s3.swapcase()) # HELLO python
    #4.title() Title The letters in the string ( Capitalize the first letter of each word )
    # character string .title()
    s4 = "hello python hello world"
    print(s4.title()) # Hello Python Hello World
    #5.capitalize() Make the first letter in the string uppercase Capital function 
    # character string .captialize()
    s5 = "hello python hello world"
    print(s5.capitalize()) # Hello python hello world
    
  • 2.2.2 Determine the content of the string
    # 1.isupper() Check whether the string is composed of uppercase letters 
    # Variable .isupper()
    # 2.islower() Check whether the string is composed of lowercase letters 
    # Variable .islower()
    # 3.istitle() Check whether the string meets the title requirements 
    # Variable .istitle()
    # 4.isalnum() Check whether the string is composed of numbers, letters and text 
    # Variable .isalnum()
    # 5.isalpha() Check whether the string is composed of letters and text 
    # Variable .isalpha()
    # 6.isdigit() Detect whether the string is 10 Hexadecimal characters ( Numbers ) *
    # True: Unicode Numbers ,byte Numbers ( Single byte ), Full angle numbers ( Double byte )
    # False: Chinese characters and numbers 
    # Error: nothing 
    # Variable .isdigit()
    # 7.isnumeric() Check whether the string is composed of numeric characters ( Numbers )
    # True: Unicode Numbers , Full angle numbers ( Double byte ), Chinese characters and numbers 
    # False: nothing 
    # Error: byte Numbers ( Single byte )
    # Variable .isnumeric()
    # 8.isspace() Detect whether the string is composed of white space characters ( Invisible characters ) form *
    # Variable .isspace()
    
  • 2.2.3 Judge what starts and ends
    # 1.startswith() Checks whether the string starts with the specified string *
    # Variable .startswith(' Detected string ')
    # 2.endswith() Checks whether the string ends with the specified string *
    # Variable .endswith(' Detected string ')
    
  • 2.2.4 Text alignment
    # 1.center() Fills the string to the specified length with the specified characters , Center the original content 
    # Variable .center( Fill length )
    # Variable .center( Fill length , Fill character )
    # 2.ljust() Fills the string to the specified length with the specified characters , Align the original content to the left 
    # Variable .ljust( Fill length )
    # Variable .ljust( Fill length , Fill character )
    # 3.rjust() Fills the string to the specified length with the specified characters , Align the original content to the right 
    # Variable .rjust( Fill length )
    # Variable .rjust( Fill length , Fill character )
    # 4.zfill() zero fill Zero fill effect ( That is, the length is not enough 0 fill ), Keep the content to the right 
    # Variable .zfill( The length of the entire string )
    
  • 2.2.5 join() 、split() as well as partition()
    # 1.split() Cut a string with a specific string *
    # Variable .split( Cut characters )
    # Variable .split( Cut characters , Number of cuts )
    # 2.join() Concatenate container data into a string using a specific string *
    # Specific string .join( Containers )
    
  • 2.2.6 Delete the blank string strip()
    # 1.strip() Remove the consecutive characters specified on the left and right sides of the string *
    # Variable .strip() By default, the left and right space characters are removed 
    # Variable .strip( Removed specified string )
    # 2.lstrip() Removes the consecutive characters specified to the left of the string 
    # Variable .lstrip() By default, the left and right space characters are removed 
    # Variable .lstrip( Removed specified string )
    # 3.rstrip() Removes the consecutive characters specified to the right of the string 
    # Variable .rstrip() By default, the left and right space characters are removed 
    # Variable .rstrip( Removed specified string )
    
  • 2.2.7 String substitution replace()
  • 2.2.8 String substitution makestran(),translate()
  • 2.2.7 String formatting operation

3. Tuple( Tuples )

  • Tuples are similar to lists , Tuple use () Express . The inner elements are separated by commas , Tuples are immutable , You cannot assign values twice , Equivalent to read-only list .

    t = (100,'xiaoming','hello',1.23)
    print(t[0]) # 100
    t[3] = 666 # This is an illegal application 
    # TypeError: 'tuple' object does not support item assignment
    

4. List( list )

  • List can complete the data structure implementation of most collection classes , Support for characters , Numbers , String, etc. . The list is Python The most common composite data type .

4.1 Common methods in the list

  • 4.1.1 append() Method
    Modify the list object in place , Add a new element to the end of the list , Fast , Recommended
    list = [10,'a']
    list.append('b')
    print(list)
    # result : [10, 'a', 'b']
    
  • 4.1.2 insert() Method
    Inserts the specified element into any specified position of the list object , This will move all elements behind the insertion position , It will affect the processing speed . When a large number of elements are involved , Avoid using . There are other functions like this movement :remove(),pop(),del(), They also move the element after the operation position when deleting the last element .
    list = [10,'a']
    list.insert(1,'b')
    print(list)
    # result : [10, 'b', 'a']
    

Be careful : append() and insert() The method is the list method , Can only be called on a list , Cannot call... On other values , For example, strings and integers .

  • 4.1.3 " + " Operator operation
    Copy the original list and the new list elements to the new list object in turn , Not really adding to the end , Instead, create a new list object . This approach involves a large number of replication operations , It is not recommended to operate on a large number of elements .
    list = [10,'a']
    list = list + ['b']
    print(list)
    # result : [10, 'a', 'b']
    
  • 4.1.4 extend() Method
    Add all elements of the target list to the end of this list , It belongs to in-situ operation , Do not create new list objects .
    list = [10,'a']
    list.extend([20,'b'])
    print(list)
    # result : [10, 'a', 20, 'b']
    

Be careful : Additional append() and Expand extend() Differences in methods :append() The method is to add the element decomposition of the data type to the list ;extend() Method to add the element as a whole .

  • 4.1.5 Multiplication extension
    Use multiplication to expand the list , Generate a new list , The new list element is a multiple repetition of the original list element . Also suitable for multiplication expansion operations are , character string , Tuples .
    list = [10,'a']
    list2 = list * 3
    print(list2)
    # result : [10, 'a', 10, 'a', 10, 'a']
    
  • 4.1.6 del The global method
    It can delete the element at the specified position in the list , You can also empty the list , Dictionaries can also be used del
    list = [10,'a','b']
    del list[1]
    print(list) # result : [10, 'b']
    del list
    print(list) # result : <class 'list'>
    
  • 4.1.7 remove() Method
    Delete the first occurrence of the specified element , If the element does not exist, an exception is thrown
    list = [10,'a','b',30,'a']
    list.remove('a')
    print(list) # result : [10, 'b', 30, 'a']
    list.remove('c')
    print(list)
    # Throw an exception 
    # Traceback (most recent call last):
    # [10, 'b', 30, 'a']
    # File "C:Desktop/Test.py", line 10, in <module>
    # list.remove('c')
    # ValueError: list.remove(x): x not in list
    

If you know the subscript of the value to be deleted in the list ,del Statements are easy to use . If you know the value you want to delete from the list ,remove() It's easy to use .

  • 4.1.8 pop() Method
    Deletes and returns the element at the specified index location , If no location is specified, the last element of the default action list ; If pop Parameter index bit exceeds , False report .
    list = [10,'a','b',30]
    print(list.pop(1)) # result : a
    print(list) # result : [10, 'b', 30]
    print(list.pop(6)) # result : IndexError: pop index out of range
    
  • 4.1.9 sort() Sorting method
    sort() You can sort a list of values or a list of strings .
    # positive sequence 
    num = [2,5,-1,3.14,8,22,10]
    num.sort()
    print(num)
    # Output : [-1, 2, 3.14, 5, 8, 10, 22]
    print(sorted(num))
    # Output : [-1, 2, 3.14, 5, 8, 10, 22]
    # sort() and sorted() Method , The usage of the two is different 
    # The reverse 
    # Appoint reverse The key parameter is True
    num = [2,5,-1,3.14,8,22,10]
    num.sort(reverse=True)
    print(num)
    # Output : [22, 10, 8, 5, 3.14, 2, -1]
    print(sorted(num,reverse=True))
    # Output : [22, 10, 8, 5, 3.14, 2, -1]
    
    About sort() The method should pay attention to :
    • sort() Method to sort the list on the spot .
      num = [2,5,-1,3.14,8,22,10]
      num = num.sort() # Wrong operation 
      print(num)
      
    • You can't sort a list that has both numbers and string values
      str1 = [1,3,5,7,'hello','world']
      str1.sort()
      print(str1)
      # TypeError: '<' not supported between instances of 'str' and 'int'
      
    • sort() Method to sort a string , Use "ASCII Character order ", Not the actual dictionary order . A lowercase letter a stay Capitalization z after .
      str1 = ['A','a','B','b','C','c']
      str1.sort()
      print(str1)
      # Output : ['A', 'B', 'C', 'a', 'b', 'c']
      # Sort in normal dictionary order 
      str2 = ['A', 'a', 'B', 'b', 'C', 'c']
      str2.sort(key=str.lower) # Treat all items in the list as lowercase 
      print(str2)
      

5. Dictionary( Dictionaries )

5.1 increase

  • 5.1.1 Give the dictionary newly added " Key value pair "
    If “ key ” Already exists , Coverage “ Old key value pairs ”, If “ key ” non-existent , Then add “ Key value pair ”.
    info = {
    'name':'zz','age':18}
    info['age'] = 20 # Key already exists , Cover 
    info['job'] = 'student' # The key doesn't exist , newly added 
    print(info) # result : {'name': 'zz', 'age': 20, 'job': 'student'}
    
  • 5.1.2 Python Dictionary update() Method
    Add all key value pairs in the new dictionary to the old dictionary object , If the key value pair has repetition, it will be overwritten directly
    info = {
    'name':'zz','age':18}
    info1 = {
    'name':'hh','sex':' male ','money':8000}
    info.update(info1)
    print(info)
    # result : {'name': 'hh', 'age': 18, 'sex': ' male ', 'money': 8000}
    

5.2 Delete

  • 5.2.1 Python Dictionary clear() Method
    Delete all elements in the dictionary
    info = {
    'name':'zz','age':18,'sex':' male '}
    info.clear()
    print(info) # result : {}
    
  • 5.2.2 Python Dictionary del The global method
    Can delete the element of the key specified in the dictionary , You can also delete the dictionary , The list can also be used del
    info = {
    'name':'zz','age':18,'sex':' male '}
    del info['name'] # Delete key is 'name' The key/value pair 
    print(info) # result : {'age': 18, 'sex': ' male '}
    del info # Empty dictionary 
    print(info)
    # Throw an exception :
    # Traceback (most recent call last):
    # {'age': 18, 'sex': ' male '}
    # File "C:/Desktop/Test.py", line 26, in <module>
    # print(info)
    # NameError: name 'info' is not defined
    
    Here you can think about , Why clear() There is no exception when deleting the dictionary ?
    because : use del The deleted dictionary no longer exists , While using clear() Is to clear all the elements in the dictionary . If you don't understand , I suggest you read it more , Experience deeply , You'll understand , At this time, I have to sigh that Chinese culture is broad and profound !!!
  • 5.2.3 Python Dictionary pop() Method
    Delete the value corresponding to the key specified in the dictionary , The return value is the deleted value
    info = {
    'name':'zz','age':18,'sex':' male '}
    print(info.pop('name')) # result : zz
    print(info) # result : {'age': 18, 'sex': ' male '}
    
  • 5.2.4 Python Dictionary popitem() Method
    Randomly return and delete a pair of keys and values in the dictionary
    info = {
    'name':'zz','age':18,'sex':' male '}
    pop_info = info.popitem() # Randomly return and delete a key value pair 
    print(pop_info)
    # The output may be : ('sex', ' male ')
    

6. Set( aggregate )

Be careful : aggregate (set) It's a Disordered non repetition Sequence of elements .

# 1. Create set 
info = set('hello')
print(info)
# Possible result : {'l', 'e', 'o', 'h'}

6.1 increase

Python There are two common ways to add collections , Namely add() and update().

  • 6.1.1 Python aggregate add() Method
    Add the element to be passed in as a whole to the collection , The insertion position is random
    info = {
    'h', 'e', 'l', 'o'}
    info.add('python')
    print(info)
    # Possible result : {'h', 'e', 'python', 'l', 'o'}
    
  • 6.1.2 Python aggregate update() Method
    Split the elements to be passed in , Pass as an individual into the collection
    info = {
    'h', 'e', 'l', 'o'}
    info.update('python')
    print(info)
    # Possible result : {'n', 'e', 't', 'o', 'h', 'y', 'p', 'l'}
    

6.2 Delete

  • 6.2.1 Python aggregate remove() Method
    Delete elements from the collection , There is no throw exception
    info = {
    'h', 'e', 'python', 'l', 'o'}
    info.remove('python')
    print(info)
    # Possible result : {'e', 'l', 'h', 'o'}
    

Articles you may be interested in :

  • Python How to determine whether a string is a decimal
  • Python in break and continue,else Explain in detail the usage and differences of

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved