Python Foundation II (base data type)

Source: Internet
Author: User

One, intro.

1 What is data?

x=10,10 is the data we want to store.

2 Why data is divided into different types

Data is used to represent States, and different States should be represented by different types of data.

3 Data types

    • Digital
    • String
    • List
    • Meta-group
    • Dictionary
    • Collection
Two basic data types. 2.1 Numeric int.

The number is mainly used for computing, not many ways to use, just remember one can:

#bit_length () The minimum number of bits to use when the decimal is in binary notation v = 11data = V.bit_length () print (data)
2.2 Boolean bool.

There are two types of Boolean values: True,false. is the correct condition of the reaction.

True 1 true.

False 0 false.

2.3 String str.

2.3.1, the index of the string, and the slice.

The index is subscript, that is, the elements of the string begin with the first, the initial index is 0, and so on.

A = ' Abcdefghijk ' Print (a[0]) print (a[3]) print (a[5]) print (a[7])

A slice is a section of a string that is intercepted by an index (index: Index: STRIDE), forming a new string (the principle is that Gu head ignores butt).

A = ' Abcdefghijk ' Print (A[0:3]) print (A[2:5]) print (a[0:]) #默认到最后print (a[0:-1]) #-1 is the last print (A[0:5:2]) #加步长
Print (A[5:0:-2]) #反向加步长

2.3.2, String common methods.

#captalize, Swapcase,titleprint (Name.capitalize ()) #首字母大写print (Name.swapcase ()) #大小写翻转msg = ' Egon say hi ' Print ( Msg.title ()) #每个单词的首字母大写 # in cohabitation, total length, padding Ret2 = A1.center ("*") print (Ret2) #数字符串中的元素出现的个数. # Ret3 = A1.count ("A", 0,4) # can slice # print (ret3) a2 = "hqw\t" #\t in front of the completion # By default, a tab key becomes 8 spaces, if the character length in front of the tab is less than 8, then complete 8, If the character in front of the TAB key is longer than 8, then complete the 16, and so on, and then complete 8. Ret4 = A2.expandtabs () print (ret4) a4 = "dkfjdkfasf54" #startswith determine whether to ... Start #endswith judge whether to ... End # Ret4 = A4.endswith (' jdk ', 3,6) # Gu Tou Ignoring butt # print (RET4) # Returns a Boolean # Ret5 = A4.startswith ("KFJ", 1,4) # print (RET5) #寻找字符串中的元素 exists # Ret6 = A4.find ("Fjdk", 1,6) # print (RET6) # Returns the index of the found element if not found return -1# ret61 = A4.index ("Fjdk", 4,6) # print (ret61) # returned to find The index of the element, unable to find an error. What #split divide and eventually form a list this list does not contain this split element. # ret9 = ' Title,tilte,atre, '. Split (' t ') # print (ret9) # ret91 = ' Title,tilte,atre, '. Rsplit (' t ', 1) # Print (ret91) # Format three gameplay formats output res= ' {} {} {} '. Format (' Egon ', ' Male ') res= ' {1} ' {0} {1} '. Format (' Egon ', ', ' Male ') res= ' {name} {age} { Sex} '. Format (sex= ' Male ', name= ' Egon ', age=18)#stripname = ' *egon** ' Print (Name.strip (' * ')) print (Name.lstrip (' * ')) print (Name.rstrip (' * ')) #replacename = ' Alex say: I have one tesla,my name is Alex ' Print (Name.replace (' Alex ', ' SB ', 1) # # # # # # # # # # # # # # # # # # #is系列name = ' jinxin123 ' Print (Name.isalnum ()) # The string consists of letters or numbers print (Name.isalpha ()) #字符串只由字母组成print (Name.isdigit ()) #字符串只由数字组成
2.4 Yuan zu tupe.

Tuples are called read-only lists, where data can be queried but cannot be modified, so the slicing of strings also applies to tuples. Example: ("A", "B", "C")

List of 2.5 lists.

The list is one of the underlying data types in Python, and other languages have data types similar to lists, such as JS called arrays, which are enclosed in [] and each element is separated by commas, and he can store various data types such as:

Li = [' Alex ', 123,ture, (Wusir), [All-in-all, ' xiaoming ',],{' name ': ' Alex '}]

Compared to strings, lists can store not only different data types, but also large amounts of data, 32-bit Python is limited to 536,870,912 elements, and 64-bit Python is limited to 1.,152,921,504,606,85e,+18 elements. And the list is ordered, there are index values, can be sliced, convenient to take value.

2.5.1 Increase

Li = [1, ' A ', ' B ', 2,3, ' a ']# li.insert (0,55) #按照索引去增加 # Print (LI) # # li.append (' aaa ') #增加到最后 # li.append ([triple]) #增加到最后 # Print (LI) # # li.extend ([' q,a,w ']) #迭代的去增 # li.extend ([' q,a,w ', ' aaa ']) # li.extend (' a ') # li.extend (' abc ') # Li.extend (' A, B,c ') # print (LI)

2.5.2 Delete

# L1 = li.pop (1) #按照位置去删除, there is a return value of # print (L1) # del Li[1:3] #按照位置去删除, also can slice delete no return value. # print (LI) # li.remove (' a ') #按照元素去删除 # Print (LI) # li.clear () #清空列表列表的删

2.5.3 Change

# change # li = [1, ' A ', ' B ', 2,3, ' a ']# li[1] = ' Dfasdfas ' # print (LI) # Li[1:3] = [' A ', ' B ']# print (LI) List change

2.5.4 Search

Slice it, or cycle it.

2.5.5, other operations.

Count (number) (the method counts the number of occurrences of an element in the list).

1 a = ["Q", "W", "Q", "R", "T", "Y"]2 print (A.count ("Q"))

Index (method used to find the index position of the first occurrence of a value from the list)

1 a = ["Q", "W", "R", "T", "Y"]2 print (A.index ("R"))

Sort (the method is used to sort the list at the original location).

Reverse (the method stores the elements in the list in reverse).

1 A = [2,1,3,4,5]2 a.sort () # He has no return value, so it can only print A3 print (a) 4 a.reverse () #他也没有返回值, so only A5 print (a) can be printed
2.6 Dictionary Dict

  A dictionary is the only type of mapping in Python that stores data in the form of key-value pairs (key-value). Python computes the hash function of key and determines the storage address of value based on the computed result, so the dictionary is stored out of order and the key must be hashed. A hash indicates that a key must be an immutable type, such as a number, a string, a tuple.

The Dictionary (dictionary) is the most flexible built-in data structure type in addition to the list of unexpected python. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

2.6.1 Increase

# dic[' li ' = ["A", "B", "C"]# print (DIC) # SetDefault adds a key-value pair to the dictionary, if only the key that corresponds to the value is none, but if the original dictionary has a set of key-value pairs, then he will not change or overwrite. # dic.setdefault (' K ', ' V ') # print (DIC)  # {' Age ': ' ' name ': ' Jin ', ' sex ': ' Male ', ' k ': ' V '}# dic.setdefault (' k ', ' v1 ')  # {' Age ': ' ' name ': ' Jin ', ' sex ': ' Male ', ' k ': ' V '}# print (DIC) dictionary

2.6.2 Delete

# Dic_pop = Dic.pop ("A", ' no key default return value ') # Pop deletes a key-value pair based on key and returns the corresponding value if no key returns the default return value # print (dic_pop) # del dic["name"]  # no return value. # print (DIC) # DIC_POP1 = Dic.popitem ()  # Randomly deletes a key-value pair in the dictionary, returns the deleted key-value pair as a Ganso return # print (DIC_POP1)  # (' Name ', ' Jin ') # Dic_ Clear = Dic.clear ()  # Empty Dictionary # Print (dic,dic_clear)  # {} None of the dictionary is deleted

2.6.3 Change

# dic = {"Name": "Jin", "Age": +, "sex": "male"}# Dic2 = {"Name": "Alex", "Weight": 75}# dic2.update (DIC)  # Add all the key-value pairs of dic (same overlay, no add) to Dic2 # print (DIC2)

2.6.4 Search

# value1 = dic["Name"]  # no error # print (value1) # # value2 = Dic.get ("DJFFDSAFG", "Default return value")  # no return value can be returned # print ( value2)

2.6.5 Other operations

# item = Dic.items () # Print (Item,type (item))  # dict_items ([' Name ', ' Jin '), (' Sex ', ' Male '), (' Age ', ')]) <class ' Dict_items ' ># This type is the Dict_items type, the iterated # keys = Dic.keys () # Print (Keys,type (keys))  # Dict_keys ([' Sex ', ' age ', ' Name ']) <class ' dict_keys ' ># values = dic.values () # Print (Values,type (values))  # dict_values ([' Male ', 18, ' Jin ']) <class ' dict_values ' > ibid.

The cycle of a dictionary

# dic = {"Name": "Jin", "Age": +, "sex": "Male"}# for key in dic:#     print (key) # for item in Dic.items (): #     Print (item) # For Key,value in Dic.items (): #     print (Key,value)
Third, other (For,enumerate,range)

For loop: The user iterates through the contents of an object in order.

msg = ' old boy python is the best Python training institution in the country ' for item in msg:    print (item) li = [' Alex ', ' Silver Horn ', ' goddess ', ' Egon ', ' Taibai ']for i in Li:    Print (i) dic = {' name ': ' Taibai ', ' age ': +, ' sex ': ' Man '}for k,v in Dic.items ():    print (K,V)

Enumerate: enumerations, for an iterative (iterable)/traversed object (such as a list, string), enumerate it into an index sequence that can be used to obtain both the index and the value.

Li = [' Alex ', ' Silver Horn ', ' goddess ', ' Egon ', ' Taibai ']for i in Enumerate (LI):    print (i) for index,name in Enumerate (li,1):    print ( Index,name) for index, name in enumerate (Li, s):  # start position default is 0, can change    print (index, name)

Range: Specifies a range that generates the specified number.

For I in Range (1,10):    print (i) for I in Range (1,10,2):  # step    print (i) for I in Range (10,1,-2): # Reverse Step    pri NT (i)

Python Foundation II (base data type)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.